首页
归档
留言
友链
广告合作
壁纸
更多
美女主播
Search
1
博瑞GE车机升级/降级
5,610 阅读
2
Mac打印机设置黑白打印
4,952 阅读
3
修改elementUI中el-table树形结构图标
4,896 阅读
4
Mac客户端添加腾讯企业邮箱方法
4,675 阅读
5
intelliJ Idea 2022.2.X破解
4,357 阅读
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
登录
/
注册
Search
标签搜索
Spring Boot
Java
Vue
Spring Cloud
Mac
MyBatis
WordPress
MacOS
asp.net
Element UI
Nacos
.Net
Spring Cloud Alibaba
MySQL
Mybatis-Plus
Typecho
jQuery
Java Script
IntelliJ IDEA
微信小程序
Laughing
累计撰写
627
篇文章
累计收到
1,421
条评论
首页
栏目
后端开发
HarmonyOS Next
Web前端
微信开发
开发辅助
App开发
数据库
随笔日记
页面
归档
留言
友链
广告合作
壁纸
美女主播
搜索到
103
篇与
的结果
2020-09-29
spring boot quartz定时任务基本使用及介绍
什么是QuartzQuartz是一个完全由java编写的开源作业调度框架,由OpenSymphony组织开源出来。所谓作业调度其实就是按照程序的设定,某一时刻或者时间间隔去执行某个代码。最常用的就是报表的制作了。Quartz基本使用添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency>创建Job/** * @author laughing * @date 2020/9/29 * @site https://www.lisen.org */ public class PrintJobService implements Job { private final Logger logger = LoggerFactory.getLogger(PrintJobService.class); /** * 任务执行 * * @param jobExecutionContext 任务执行信息 */ @Override public void execute(JobExecutionContext jobExecutionContext) { logger.info("准备获取scheduler参数"); try { String schedulerValue = jobExecutionContext.getScheduler().getContext().getString("sKey"); logger.info(schedulerValue); } catch (SchedulerException e) { e.printStackTrace(); } logger.info("完成获取scheduler参数\n"); logger.info("准备获取TriggerData"); JobDataMap triggerDataMap = jobExecutionContext.getTrigger().getJobDataMap(); for (String triggerKey : triggerDataMap.getKeys()) { logger.info(triggerDataMap.getString(triggerKey)); } logger.info("完成获取TriggerData\n"); logger.info("准备获取JobData"); JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap(); for (String triggerKey : jobDataMap.getKeys()) { logger.info(jobDataMap.getString(triggerKey)); } logger.info("完成获取JobData"); } }使用/** * @author laughing * @date 2020/9/29 * @site https://www.lisen.org */ @RestController public class QuartzController { @RequestMapping("/quartz") public String quartz() throws SchedulerException { //创建一个scheduler Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); //通过scheduler传参数 scheduler.getContext().put("sKey", "sValue"); //创建一个Trigger Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("trigger1", "group1") .usingJobData("t1", "tv1") //3秒执行一次 .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3) //执行1次 .withRepeatCount(0)) .build(); trigger.getJobDataMap().put("t2", "tv2"); //创建一个job JobDetail job = JobBuilder.newJob(PrintJobService.class) .usingJobData("j1", "jv1") .withIdentity("myJob", "myGroup").build(); job.getJobDataMap().put("j2", "jv2"); //注册trigger并启动scheduler scheduler.scheduleJob(job, trigger); scheduler.start(); return "success"; } }Quartz的基本组成一、调度器(Scheduler)调度器用来管理触发器和作业。Trigger和JobDetail可以注册到Scheduler中,两者在Scheduler中都拥有自己的唯一的组和名称用来进行彼此的区分,Scheduler可以通过组名或者名称来对Trigger和JobDetail来进行管理。一个Trigger只能对应一个Job,但是一个Job可以对应多个Trigger。每个Scheduler都包含一个SchedulerContext,用来保存Scheduler的上下文。Job和Trigger都可以获取SchedulerContext中的信息。Scheduler包含两个重要的组件,JobStore和ThreadPool。JobStore用来存储运行时信息,包括Trigger,Schduler,JobDetail,业务锁等。它有多种实现RAMJob(内存实现),JobStoreTX(JDBC,事务由Quartz管理)等。ThreadPool就是线程池,Quartz有自己的线程池实现。所有任务的都会由线程池执行。Scheduler是由SchdulerFactory创建,它有两个实现:DirectSchedulerFactory和StdSchdulerFactory。前者可以用来在代码里定制你自己的Schduler参数。后者是直接读取classpath下的quartz.properties(不存在就都使用默认值)配置来实例化Schduler。通常来讲,我们使用StdSchdulerFactory也就足够了二、触发器(Trigger)Trigger是用来定义Job的执行规则,直白的说就是什么时间、重复多少次。主要有四种触发器,其中SimpleTrigger和CronTrigger触发器用的最多。SimpleTrigger从某一个时间开始,以一定的时间间隔来执行任务。它主要有两个属性,repeatInterval 重复的时间间隔;repeatCount重复的次数,实际上执行的次数是n+1,因为在startTime的时候会执行一次。CronTrigger适合于复杂的任务,使用cron表达式来定义执行规则。CalendarIntervalTrigger类似于SimpleTrigger,指定从某一个时间开始,以一定的时间间隔执行的任务。 但是CalendarIntervalTrigger执行任务的时间间隔比SimpleTrigger要丰富,它支持的间隔单位有秒,分钟,小时,天,月,年,星期。相较于SimpleTrigger有两个优势:1、更方便,比如每隔1小时执行,你不用自己去计算1小时等于多少毫秒。 2、支持不是固定长度的间隔,比如间隔为月和年。但劣势是精度只能到秒。它的主要两个属性,interval 执行间隔;intervalUnit 执行间隔的单位(秒,分钟,小时,天,月,年,星期)DailyTimeIntervalTrigger指定每天的某个时间段内,以一定的时间间隔执行任务。并且它可以支持指定星期。它适合的任务类似于:指定每天9:00 至 18:00 ,每隔70秒执行一次,并且只要周一至周五执行。它的属性有startTimeOfDay 每天开始时间;endTimeOfDay 每天结束时间;daysOfWeek 需要执行的星期;interval 执行间隔;intervalUnit 执行间隔的单位(秒,分钟,小时,天,月,年,星期);repeatCount 重复次数所有的trigger都包含了StartTime和endTIme这两个属性,用来指定Trigger被触发的时间区间。所有的trigger都可以设置MisFire策略,该策略是对于由于系统奔溃或者任务时间过长等原因导致trigger在应该触发的时间点没有触发,并且超过了misfireThreshold设置的时间(默认是一分钟,没有超过就立即执行)就算misfire了,这个时候就该设置如何应对这种变化了。激活失败指令(Misfire Instructions)是触发器的一个重要属性,它指定了misfire发生时调度器应当如何处理。所有类型的触发器都有一个默认的指令,叫做Trigger.MISFIRE_INSTRUCTION_SMART_POLICY,但是这个这个“聪明策略”对于不同类型的触发器其具体行为是不同的。对于SimpleTrigger,这个“聪明策略”将根据触发器实例的状态和配置来决定其行 为。具体如下:如果Repeat Count=0:只执行一次instruction selected = MISFIRE_INSTRUCTION_FIRE_NOW;如果Repeat Count=REPEAT_INDEFINITELY:无限次执行instruction selected = MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT;如果Repeat Count>0: 执行多次(有限)instruction selected = MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT;SimpleTrigger常见策略:MISFIRE_INSTRUCTION_FIRE_NOW 立刻执行。对于不会重复执行的任务,这是默认的处理策略。MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT 在下一个激活点执行,且超时期内错过的执行机会作废。MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_COUNT 立即执行,且超时期内错过的执行机会作废。MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT 在下一个激活点执行,并重复到指定的次数。MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_COUNT 立即执行,并重复到指定的次数。MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY 忽略所有的超时状态,按照触发器的策略执行。对于CronTrigger,该“聪明策略”默认选择MISFIRE_INSTRUCTION_FIRE_ONCE_NOW以指导其行为。CronTrigger常见策略:MISFIRE_INSTRUCTION_FIRE_ONCE_NOW 立刻执行一次,然后就按照正常的计划执行。MISFIRE_INSTRUCTION_DO_NOTHING 目前不执行,然后就按照正常的计划执行。这意味着如果下次执行时间超过了end time,实际上就没有执行机会了。三、作业(Job)Job是一个任务接口,开发者定义自己的任务须实现该接口实现void execute(JobExecutionContext context)方法,JobExecutionContext中提供了调度上下文的各种信息。Job中的任务有可能并发执行,例如任务的执行时间过长,而每次触发的时间间隔太短,则会导致任务会被并发执行。如果是并发执行,就需要一个数据库锁去避免一个数据被多次处理。可以在execute()方法上添加注解@DisallowConcurrentExecution解决这个问题。四、作业详情(JobDetail)Quartz在每次执行Job时,都重新创建一个Job实例,所以它不直接接受一个Job的实例,相反它接收一个Job实现类,以便运行时通过newInstance()的反射机制实例化Job。因此需要通过一个类来描述Job的实现类及其它相关的静态信息,如Job名字、描述、关联监听器等信息,JobDetail承担了这一角色。所以说JobDetail是任务的定义,而Job是任务的执行逻辑。五、日历(Calendar)Calendar:org.quartz.Calendar和java.util.Calendar不同,它是一些日历特定时间点的集合(可以简单地将org.quartz.Calendar看作java.util.Calendar的集合——java.util.Calendar代表一个日历时间点,无特殊说明后面的Calendar即指org.quartz.Calendar)。一个Trigger可以和多个Calendar关联,以便排除或包含某些时间点。主要有以下CalendarHolidayCalendar:指定特定的日期,比如20140613。精度到天。DailyCalendar:指定每天的时间段(rangeStartingTime, rangeEndingTime),格式是HH:MM[:SS[:mmm]],也就是最大精度可以到毫秒。WeeklyCalendar:指定每星期的星期几,可选值比如为java.util.Calendar.SUNDAY。精度是天。MonthlyCalendar:指定每月的几号。可选值为1-31。精度是天AnnualCalendar: 指定每年的哪一天。使用方式如上例。精度是天。CronCalendar:指定Cron表达式。精度取决于Cron表达式,也就是最大精度可以到秒。六、JobDataMap用来保存JobDetail运行时的信息,JobDataMap的使用:.usingJobData("name","kyle")或者.getJobDataMap("name","kyle")七、cron表达式Cron表达式对特殊字符的大小写不敏感,对代表星期的缩写英文大小写也不敏感。星号(*):可用在所有字段中,表示对应时间域的每一个时刻,例如, 在分钟字段时,表示“每分钟”;问号(?):该字符只在日期和星期字段中使用,它通常指定为“无意义的值”,相当于点位符;减号(-):表达一个范围,如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12;逗号(,):表达一个列表值,如在星期字段中使用“MON,WED,FRI”,则表示星期一,星期三和星期五;斜杠(/):x/y表达一个等步长序列,x为起始值,y为增量步长值。如在分钟字段中使用0/15,则表示为0,15,30和45秒,而5/15在分钟字段中表示5,20,35,50,你也可以使用*/y,它等同于0/y;L:该字符只在日期和星期字段中使用,代表“Last”的意思,但它在两个字段中意思不同。L在日期字段中,表示这个月份的最后一天,如一月的31号,非闰年二月的28号;如果L用在星期中,则表示星期六,等同于7。但是,如果L出现在星期字段里,而且在前面有一个数值X,则表示“这个月的最后X天”,例如,6L表示该月的最后星期五;W:该字符只能出现在日期字段里,是对前导日期的修饰,表示离该日期最近的工作日。例如15W表示离该月15号最近的工作日,如果该月15号是星期六,则匹配14号星期五;如果15日是星期日,则匹配16号星期一;如果15号是星期二,那结果就是15号星期二。但必须注意关联的匹配日期不能够跨月,如你指定1W,如果1号是星期六,结果匹配的是3号星期一,而非上个月最后的那天。W字符串只能指定单一日期,而不能指定日期范围;LW组合:在日期字段可以组合使用LW,它的意思是当月的最后一个工作日;井号(#):该字符只能在星期字段中使用,表示当月某个工作日。如6#3表示当月的第三个星期五(6表示星期五,#3表示当前的第三个),而4#5表示当月的第五个星期三,假设当月没有第五个星期三,忽略不触发;C:该字符只在日期和星期字段中使用,代表“Calendar”的意思。它的意思是计划所关联的日期,如果日期没有被关联,则相当于日历中所有日期。例如5C在日期字段中就相当于日历5日以后的第一天。1C在星期字段中相当于星期日后的第一天。八、quartz.properties文件编写RAMJob的配置####################RAMJob的配置################## #在集群中每个实例都必须有一个唯一的instanceId,但是应该有一个相同的instanceName【默认“QuartzScheduler”】【非必须】 org.quartz.scheduler.instanceName = MyScheduler #Scheduler实例ID,全局唯一,【默认值NON_CLUSTERED】,或者可以使用“SYS_PROP”通过系统属性设置id。【非必须】 org.quartz.scheduler.instanceId=AUTO # 线程池的实现类(定长线程池,几乎可满足所有用户的需求)【默认null】【必须】 org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool # 指定线程数,至少为1(无默认值)(一般设置为1-100直接的整数合适)【默认-1】【必须】 org.quartz.threadPool.threadCount = 25 # 设置线程的优先级(最大为java.lang.Thread.MAX_PRIORITY 10,最小为Thread.MIN_PRIORITY 1)【默认Thread.NORM_PRIORITY (5)】【非必须】 org.quartz.threadPool.threadPriority = 5 #misfire设置的时间默认为一分钟 org.quartz.jobStore.misfireThreshold=60000 # 将schedule相关信息保存在RAM中,轻量级,速度快,遗憾的是应用重启时相关信息都将丢失。 org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore # 建议设置为“org.terracotta.quartz.skipUpdateCheck=true”不会在程序运行中还去检查quartz是否有版本更新。【默认false】【非必须】 org.quartz.scheduler.skipUpdateCheck = truejdbcJobStore配置###################jdbcJobStore############################ org.quartz.scheduler.instanceName=MyScheduler org.quartz.scheduler.instanceId=AUTO org.quartz.threadPool.threadCount=3 # 所有的quartz数据例如job和Trigger的细节信息被保存在内存或数据库中,有两种实现:JobStoreTX(自己管理事务) #和JobStoreCMT(application server管理事务,即全局事务JTA) org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX # 类似于Hibernate的dialect,用于处理DB之间的差异,StdJDBCDelegate能满足大部分的DB org.quartz.jobStore.driverDelegateClass =org.quartz.impl.jdbcjobstore.StdJDBCDelegate #数据库表的前缀 org.quartz.jobStore.tablePrefix=QRTZ_ #配置数据源的名称 org.quartz.jobStore.dataSource=myDS #为了指示JDBCJobStore所有的JobDataMaps中的值都是字符串,并且能以“名字-值”对的方式存储而不是以复杂对象的序列化形式存储在BLOB字段中,应该设置为true(缺省方式) org.quartz.jobStore.useProperties = true # 检入到数据库中的频率(毫秒)。检查是否其他的实例到了应当检入的时候未检入这能指出一个失败的实例, #且当前Scheduler会以此来接管执行失败并可恢复的Job通过检入操作,Scheduler也会更新自身的状态记录 org.quartz.jobStore.clusterCheckinInterval=20000 # 是否集群、负载均衡、容错,如果应用在集群中设置为false会出错 org.quartz.jobStore.isClustered=false #misfire时间设置 org.quartz.jobStore.misfireThreshold=60000 # 连接超时重试连接的间隔。使用 RamJobStore时,该参数并没什么用【默认15000】【非必须】 #org.quartz.scheduler.dbFailureRetryInterval = 15000 #下面是数据库链接相关的配置 org.quartz.dataSource.myDS.driver=com.mysql.jdbc.Driver org.quartz.dataSource.myDS.URL=jdbc:mysql://localhost:3306/zproject?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC org.quartz.dataSource.myDS.user=root org.quartz.dataSource.myDS.password=root org.quartz.dataSource.myDS.maxConnections=5参考资料quartz基本介绍和使用
2020年09月29日
1,213 阅读
0 评论
0 点赞
2020-09-28
Spring Boot 配合nginx完成跨域配置
在 springboot配置跨域 我们介绍了spring boot两种配置跨域的方式。实际项目中,我用的一般是通过nginx进行跨域设置。nginx跨域实现的几个目标肯定是能正常跨域访问为了方便跨域,我们一般对后台api进行封装,统一返回一个前缀作为区分我们先来实现第二个目标,统一后端返回的api地址。方法一、通过yaml配置通过配置文件设置server: servlet: context-path: /api这样,我们在前端的请求,都会自动加上'/api'前缀。但是这样的设置存在两个问题:所有的请求全部都是'/api'前缀。静态资源要求带'/api'前缀。所以,我们需要通过更优雅的方式来进行设置,也就是方法二。方法二、通过实现WebMvcConfigurer接口的configurePathMatch方法首先我们在配置文件,增加自定义的前缀#配置api前缀 request-path: api-path: /api注入配置信息/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration @ConfigurationProperties(prefix = "request-path") @Data public class RequestPathProperties { private String apiPath; }增加自定义注解/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController @Target({ElementType.TYPE}) @Documented @RequestMapping @Retention(RetentionPolicy.RUNTIME) public @interface ApiRestController { /** * Alias for {@link RequestMapping#name}. */ @AliasFor(annotation = RequestMapping.class) String name() default ""; /** * Alias for {@link RequestMapping#value}. */ @AliasFor(annotation = RequestMapping.class) String[] value() default {}; /** * Alias for {@link RequestMapping#path}. */ @AliasFor(annotation = RequestMapping.class) String[] path() default {}; }增加实现WebMvcConfigurer的configurePathMatch方法,配置前缀/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Resource RequestPathProperties requestPathProperties; @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix(requestPathProperties.getApiPath(), c->c.isAnnotationPresent(ApiRestController.class)); } }经过如上配置,我们所有注解@ApiRestController的请求,都会增加'/api'前缀增加两个配置类,一个通过@ApiRestController注解,一个通过普通的@RestController注解,分别访问测试/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @ApiRestController public class NginxCorsController { @RequestMapping("/nginxCors") public String nginxCors(){ return "nginxCors"; } }/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class NormalController { @RequestMapping("/normal") public String normal(){ return "normal"; } }支持,完成了spring boot后台统一api地址的目标nginx配置跨域前端代码我们先配置前端页面,发起一个简单的post请求<!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> </head> <body> <div id="myDiv"></div> <script> $(document).ready(function () { $.ajax({ url: "/api/nginxCors", type:"post", async: false, success:function(data){ $("#myDiv").html(data); } }); }); </script> </body> </html>nginx配置我们要配置的规则很简单,所有/api开头的请求,全部重定向到后端spring boot上。打开nginx配置文件,我这里使用的是默认的,及'nginx.conf'修改locationserver { listen 1234; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #简单配置跨域 location /api { proxy_pass http://localhost:8080/api/; } location / { root html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }重新加载nginx配置文件这里用的win,linux需要对应替换命令nginx.exe -s reload打开页面测试,可以看到能够正常跨域
2020年09月28日
1,752 阅读
0 评论
0 点赞
2020-09-27
SpringBoot 之 @ControllerAdvice使用场景
SpringBoot 之 @ControllerAdvice使用场景@ControllerAdvice是spring 3.2版本增加的一个注解,@ControllerAdvice注解的类,可以应用到所有的@RequestMapping请求中,主要有三个应用场景:@ExceptionHandler 全局异常处理@InitBinder 全局数据预处理@ModelAttribute 全局数据绑定注意如果这三个注解直接在@Controller类中使用,则只对当前控制器生效如果@ControllerAdvice中不需要返回view,也可以使用@RestControllerAdvice,即@RestControllerAdvice = @ControllerAdvice + @ResponseBody@ExceptionHandler 全局异常处理定义全局异常处理类/** * 全局异常处理 * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestControllerAdvice public class GlobalExceptionHandler { /** * 处理越界异常 * @param indexOutOfBoundsException 越界异常 * @return Map */ @ExceptionHandler(IndexOutOfBoundsException.class) public Map<String,Object> indexOutOfBoundsException(IndexOutOfBoundsException indexOutOfBoundsException){ Map<String,Object> map = new HashMap<>(2); map.put("code",400); map.put("msg","越界异常"); return map; } /** * 处理空引用异常 * @param nullPointerException 空引用 * @return Map */ @ExceptionHandler(NullPointerException.class) public Map<String,Object> nullPointerException(NullPointerException nullPointerException){ Map<String,Object> map = new HashMap<>(2); map.put("code",400); map.put("msg","空引用异常"); return map; } }@RestControllerAdvice注解到类上,@ExceptionHandler注解到具体的异常上,只有@ExceptionHandler注解的异常,才会进行处理,如上,系统只会处理IndexOutOfBoundsException以及NullPointerException异常,其他异常均不进行处理。使用/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class TestGlobalExceptionController { /** * 测试越界异常 * * @return String */ @RequestMapping("/testIndexOutOfBoundsException") public String testIndexOutOfBoundsException() { String[] names = {"张三"}; return names[2]; } /** * 测试空引用异常 * * @return String */ @RequestMapping("/testNullPointerException") public String testNullPointerException() { String firstName = null; String lastName = "laughing"; return firstName.toLowerCase() + lastName; } /** * 这个异常不会被处理 * * @return String */ @RequestMapping("/exception") public String testException() throws Exception { throw new Exception("这个异常不会被处理"); } }我们分别进行请求测试@InitBinder 全局数据预处理全局数据预处理可以在@RequestMapping方法前,先对数据进行处理,然后在进入@RequestMapping方法。定义全局数据预处理类/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestControllerAdvice public class GlobalDataBinder { @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { Date date = null; try { if (text != null) { date = DateUtils.addDays(DateUtils.parseDate(text,"yyyy-MM-dd"),1); } } catch (ParseException e) { } setValue(date); } }); } }使用 @ModelAttribute @RequestMapping("/testGlobalDataBinderController") public Person testGlobalDataBinderController(@RequestParam("name") String name, @RequestParam("birthday")Date birthday){ Person person = new Person(); person.setBirthday(birthday); person.setName(name); return person; } @ModelAttribute @RequestMapping("/testGlobalDataBinderControllerBody") public Person testGlobalDataBinderControllerBody(@RequestBody Person person){ return person; } }我们通过postman测试,可以发现日期已经自动加了一天@ModelAttribute 全局数据绑定全局数据绑定功能可以用来做一些初始化的数据操作,我们可以将一些公共的数据定义在添加了 @ControllerAdvice注解的类中,这样,在每一个 Controller 的接口中,就都能够访问导致这些数据。定义全局数据绑定/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class TestGlobalDataAttributeController { /** * 全局数据绑定 * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestControllerAdvice public class GlobalDataAttribute { @ModelAttribute(name = "person") public Map<String,Object> modelAttribute(){ Map<String,Object> map = new HashMap<>(); map.put("name","张三"); return map; } }使用全局数据绑定/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class TestGlobalDataAttributeController { /** * 测试 * @param person 绑定模型 * @return 绑定数据 */ @RequestMapping("/testGlobalDataAttribute") public Map<String, Object> testDataBinder(@ModelAttribute("person") Map<String, Object> person) { return person; } }
2020年09月27日
1,267 阅读
0 评论
0 点赞
2020-09-27
Spring Boot条件注解
什么是条件注解@Conditional 根据满足某一个特定条件创建一个特定的 Bean。就是根据特定条件来控制 Bean 的创建行为,这样我们可以利用这个特性进行一些自动的配置。Spring boot 中大量用到了条件注解简单实践以不同的操作系统作为条件,我们将通过实现 CommandCondition 接口,并重写其 matches() 方法来构造判断条件。若在 Windows 系统下运行程序,则输出列表命令为 dir ,若在 Linux 系统或者Mac下运行程序,则输出列表命令为 ls创建工程这里我们只创建简单的maven工程,而不是spring boot工程。打开idea,选择创建工程。向导界面,选择Maven→勾选create from archetype,选择org.apache.maven.archetypes:maven-archetype-quickstart输入工程信息设置maven引入依赖打开pom.xml文件,增加spring依赖 <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.9.RELEASE</version> </dependency>定义接口/** * 定义接口 * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public interface CommandCondition { /** * 获取命令 * @return win返回dir,linux及mac返回ls */ public String getCommand(); }定义接口实现类定义三个接口实现类,分别继承CommandCondition接口/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class MacCommand implements CommandCondition{ /** * 获取命令 * * @return win返回dir,linux及mac返回ls */ @Override public String getCommand() { return "ls"; } }/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class LinuxCommand implements CommandCondition{ /** * 获取命令 * * @return win返回dir,linux及mac返回ls */ @Override public String getCommand() { return "ls"; } }/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class WindowsCommand implements CommandCondition{ /** * 获取命令 * * @return win返回dir,linux及mac返回ls */ @Override public String getCommand() { return "dir"; } }定义条件类定义三个条件类,分别实现matches() 方法,用来构造判断条件/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class LinuxCommandContidion implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return Objects.requireNonNull(conditionContext.getEnvironment().getProperty("os.name")).contains("Linux"); } }/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class MacCommandContidion implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return Objects.requireNonNull(conditionContext.getEnvironment().getProperty("os.name")).contains("Mac"); } }/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class WindowsCommandContidion implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return Objects.requireNonNull(conditionContext.getEnvironment().getProperty("os.name")).contains("Windows"); } }定义配置类定义配置类,注入根据条件注入Bean/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration public class CommandConfig { @Bean @Conditional(LinuxCommandContidion.class) public CommandCondition linuxCommand(){ return new LinuxCommand(); } @Bean @Conditional(MacCommandContidion.class) public CommandCondition macCommand(){ return new MacCommand(); } @Bean @Conditional(WindowsCommandContidion.class) public CommandCondition windowsCommand(){ return new WindowsCommand(); } }使用在main函数中,创建一个 AnnotationConfigApplicationContext 实例用来加载 Java 配置类,并注册我们的配置类,然后刷新容器。容器刷新完成后,我们就可以从容器中去获取 CommandCondition 的实例了,这个实例会根据操作系统不同,返回不同的命令。/** * Hello world! */ public class App { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(CommandConfig.class); annotationConfigApplicationContext.refresh(); CommandCondition commandCondition = annotationConfigApplicationContext.getBean(CommandCondition.class); String command = commandCondition.getCommand(); System.out.println(command); } }测试通过java -jar命令在不同操作系统分别运行jar包,查看输出java -jar conditional-1.0-SNAPSHOT-jar-with-dependencies.jar生成jar包运行说明jar包无法运行默认情况下,直接生成的jar包是没有配置入口类并且不包含依赖的。所以会报以下错误解决我们需要在pom.xml中增加打包插件maven-assembly-plugin<!-- 打包方式:mvn package assembly:single --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.5.5</version> <configuration> <archive> <manifest> <mainClass>org.lisen.condition.App</mainClass> </manifest> </archive> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>assembly</goal> </goals> </execution> </executions> </plugin>重新mvn install我们会得到两个jar包,名称带-with-dependencies是包含依赖的,也是我们可以通过java -jar 命令运行的。参考资料条件注解,spring boot的基石
2020年09月27日
1,287 阅读
0 评论
0 点赞
2020-09-26
徒手撸一个Spring Boot Starter,学习自动化配置
what-are-spring-boot-starter-jars(spring boot中的starter是干啥的)Spring Boot Starter是在SpringBoot组件中被提出来的一种概念,stackoverflow上面已经有人概括了这个starter是什么东西,想看完整的回答戳这里下面摘抄一段Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project, and you are good to go。扔到百度翻译里面翻译下:starter pom是一组方便的依赖描述符,可以包含在应用程序中。您可以获得所需的所有Spring和相关技术的一站式服务,而不必搜索示例代码和复制粘贴大量依赖描述符。例如,如果您想开始使用Spring和JPA进行数据库访问,只需在项目中包含springbootstarterdatajpa依赖项,就可以开始了。其实说白了,就是把一些重复的、机械的工作合成起来。如何自定义自己的starter其实starter也只是一个普通的maven工程,关于starter工程的命令,可以参考官方文档创建一个starter基本包含以下几个步骤:创建一个maven项目,关于项目的命名你可以参考考官方文档创建一个ConfigurationProperties用于保存你的配置信息增加starter实现类创建一个AutoConfiguration,引用定义好的配置信息把AutoConfiguration类加入spring.factories配置文件中进行声明打包项目并推送到maven仓库新建SpringBoot项目引入starter依赖并使用。下面的演示,我们创建一个starter,能够根据配置的url,打印并输出对应页面的内容,同时如果不传递参数,自动打印李森的博客https://lisen.cc的首页第一步创建工程并修改对应的xml文件创建工程后,需要修改对应的pom.xml文件,并增加依赖,具体修改内容如下:注意这里面的几个坑自定义的starter是不能有启动入口的!即:只能作为工具类!所以我们必须把启动类删除掉。否者,在依赖的工程里面无法引入类。需要把pom.xml的build节点全部删掉,不然无法install或者deploy。创建一个ConfigurationProperties用于保存你的配置信息先修改application.yaml文件,增加默认配置blog: url: https://lisen.cc增加配置类,并注入配置文件 /** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @ConfigurationProperties(prefix = "blog") public class BlogPropertes { private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }增加starter实现类我的实现类只是简单的通过jsoup打印并返回一个html的内容。** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ public class PrintHtmlService { public void setUrl(String url) { this.url = url; } private String url; /** * 打印并返回html内容 * @return * @throws IOException */ public String print() throws IOException { Document document = Jsoup.parse(new URL(this.url), 300 * 1000); String htmlString = document.html(); System.out.println(htmlString); return htmlString; } }创建一个AutoConfiguration,引用定义好的配置信息/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration @EnableConfigurationProperties(BlogPropertes.class) @ConditionalOnClass(PrintHtmlService.class) public class AutoConfiguration { @Resource BlogPropertes blogPropertes; @Bean @ConditionalOnClass public PrintHtmlService printHtmlService(){ PrintHtmlService printHtmlService = new PrintHtmlService(); printHtmlService.setUrl(blogPropertes.getUrl()); return printHtmlService; } }@Configuration标识本类是配置类(相当于spring中application.xml)@EnableConfigurationProperties(AutoConfigruationProperties.class)如果AutoConfigruationProperties中有注解@ConfigurationProperties 那么这个类就会被加到spring上下文的容器中,也就是可以通过@Resource来注入@ConditionalOnClass当类路径下有指定类的情况下 才进行下一步@ConditionalOnMissingBean当spring容器中没有这个Bean的时候才进行下一步把AutoConfiguration类加入spring.factories配置文件中进行声明在resources文件夹增加META-INF在META-INF文件夹下增加spring.factories文件,并设置自动装配org.springframework.boot.autoconfigure.EnableAutoConfiguration = org.lisen.printhtmlstarter.config.AutoConfiguration打包项目并推送到maven仓库如果有maven私服,可以推送到远程仓库,我这里只是自己测试,所以直接install到自己本地仓库mvn package install新建SpringBoot项目引入starter依赖并使用我这里直接新建一个普通的web项目,加入pringt-html-starter依赖进行测试新建项目并加入依赖第一次我们先不重写默认的url新建一个测试类,代码如下:/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class TestController { @Resource PrintHtmlService printHtmlService; @RequestMapping("/print") public String print() throws IOException { return printHtmlService.print(); } }通过测试,我们可以发现,正常输入了默认的https://lisen.cc的内容第二次我们修改配置文件,重写url为http://www.baidu.com修改配置文件如下,blog: url: https://www.baidu.com再次请求,我们发现,正常输出了百度的首页
2020年09月26日
1,119 阅读
0 评论
0 点赞
2020-09-24
Spring Boot配置文件详解
关于配置文件springboot有两种格式的配置文件,即yaml和properties,两种配置文件在功能上完全等效。相对于 properties而言,yaml更加简洁明了,而且使用的场景也更多。除了简洁,yaml还有另外一个特点,就是yaml中的数据是有序的,properties 中的数据是无序的关于yaml以及properties详细使用方法,我们稍后开贴专门说明,这里不再赘述。配置文件加载顺序默认情况下,springboot应用会依次从以下位置加载配置文件:项目根目录下的config文件夹项目根目录resources目录下的config文件夹resources目录这四个是默认的位置,我们可以简单验证一下。在项目根目录下config文件夹下的application.yaml,设置端口为6666server: port: 6666启动项目,我们可以看到,默认端口已经是6666自定义配置文件位置除了上述的四个默认加载配置文件的位置,我们也可以自定义文件位置。通过pring.config.location 即可指定加载配置文件位置Idea调试时动态指定配置文件位置举个栗子,我在resources文件夹下面建立一个blog文件夹,并将 application.yaml 文件放到blog文件夹下,同时设置端口为6666加入创建配置文件,并按照如下设置修改Idea配置信息spring.config.location=classpath:/blog/一定要注意配置文件位置,最后的/不能少,否则会报错运行程序,我们会发现端口变成了 6666运行jar包是动态指定配置文件位置除了在Idea调试,我们终归要将程序发不成jar包,那么jar包如何加载配置文件呢?我们是以上面的程序进行说明,此时,我们将配置文件单独拿出来,同时将resource\blog文件夹删掉。并通过mvn package将程序打包成jar包,打包后的jar包名称为properties-0.0.1-SNAPSHOT.jar ,然后我们将jar包及application.yaml文件放到一起。我们通过java -jar properties-0.0.1-SNAPSHOT.jar --spring.config.location = ./运行程序,通过控制台,我们可以看到此时端口仍然是6666,证明已经加载我们的配置文件。自定义配置文件名自定义配置文件名的方式,与自定义配置文件的方式类似,同时两个命令可以一起使用。spring.config.name这里只展示一下用java -jar命令运行的方式,我把application.yaml文件改成blog.yaml,内容不变。java -jar properties-0.0.1-SNAPSHOT.jar --spring.config.location=./ --spring.config.name=blog可以看到,程序依然以6666端口成功启动。自定义配置文件加载顺序上面说了工程内的配置文件就自定义配置文件,如果自定义配置文件与默认配置文件同时存在,那么springboot如何加载呢。新建工程修改application.propertes端口号改成1234package打包工程使用java -jar 命令加载配置文件,并制定端口为4321我们看到,程序先加载了环境变量中的配置信息
2020年09月24日
1,285 阅读
1 评论
0 点赞
2020-08-22
SpringBoot @Transactional声明事务无效问题
Spring之所以可以对开启@Transactional的方法进行事务管理,是因为Spring为当前类生成了一个代理类,然后在执行相关方法时,会判断这个方法有没有@Transactional注解,如果有的话,则会开启一个事务。但是,上面同一个类中A调用方式时,在调用B时,使用的并不是代理对象,从而导致this.B(i)时也不是代理对象,从而导致@Transactional失败。所以,Spring 从同一个类中的某个方法调用另一个有注解(@Transactional)的方法时,事务会失效,些事务的时候一定要注意到这一点。
2020年08月22日
1,075 阅读
0 评论
0 点赞
2019-11-01
Spring Boot手工开启、回滚事务
添加注解@Autowired PlatformTransactionManager platformTransactionManager; @Autowired TransactionDefinition transactionDefinition;启用事务TransactionStatus transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);提交事务platformTransactionManager.commit(transactionStatus);回滚事务platformTransactionManager.rollback(transactionStatus);
2019年11月01日
1,291 阅读
0 评论
0 点赞
2019-07-28
Spring Boot原生异步请求API说明
异步请求api调用说明在编写实际代码之前,我们来了解下一些关于异步请求的api的调用说明。获取AsyncContext:根据HttpServletRequest对象获取AsyncContext asyncContext = request.startAsync(); 设置监听器:可设置其开始、完成、异常、超时等事件的回调处理public interface AsyncListener extends EventListener { void onComplete(AsyncEvent event) throws IOException; void onTimeout(AsyncEvent event) throws IOException; void onError(AsyncEvent event) throws IOException; void onStartAsync(AsyncEvent event) throws IOException; }说明onStartAsync:异步线程开始时调用onError:异步线程出错时调用onTimeout:异步线程执行超时调用onComplete:异步执行完毕时调用一般上,我们在超时或者异常时,会返回给前端相应的提示,比如说超时了,请再次请求等等,根据各业务进行自定义返回。同时,在异步调用完成时,一般需要执行一些清理工作或者其他相关操作。需要注意的是只有在调用request.startAsync前将监听器添加到AsyncContext,监听器的onStartAsync方法才会起作用,而调用startAsync前AsyncContext还不存在,所以第一次调用startAsync是不会被监听器中的onStartAsync方法捕获的,只有在超时后又重新开始的情况下onStartAsync方法才会起作用。设置超时:通过setTimeout方法设置,单位:毫秒。一定要设置超时时间,不能无限等待下去,不然和正常的请求就一样了。Servlet方式实现异步请求面已经提到,可通过HttpServletRequest对象中获得一个AsyncContext对象,该对象构成了异步处理的上下文。所以,我们来实际操作下。编写一个简单控制层package Cc.LiSen.Controllers; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * ClassName: AsyncController <br/> * Description: <br/> * date: 2019/7/28 16:06<br/> * * @since JDK 1.8 */ @RestController @Api(tags = "测试异步请求") @ResponseBody @RequestMapping(value = "/AsyncTest") public class ServletAsyncController { private final static Logger logger = LoggerFactory.getLogger(ServletAsyncController.class); @PostMapping(value = "test") @ApiOperation(value = "测试异步请求") public void test(HttpServletRequest request, HttpServletResponse response) { AsyncContext context = request.startAsync(); context.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { logger.info("执行完成"); } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { logger.info("执行超时:"); } @Override public void onError(AsyncEvent asyncEvent) throws IOException { logger.info("发生错误:" + asyncEvent.getThrowable()); } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { logger.info("开始执行:"); } }); //设置超时 context.setTimeout(2000); //开启线程 context.start(new Runnable() { @Override public void run() { try{ Thread.sleep(100); logger.info("内部线程:"+Thread.currentThread().getName()); context.getResponse().setCharacterEncoding("UTF-8"); context.getResponse().setContentType("text/html;charset=utf-8"); context.getResponse().getWriter().println("这是内部线程"); //异步请求完成通知 //此时整个请求才完成 //其实可以利用此特性 进行多条消息的推送 把连接挂起。。 context.complete(); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); //此时之类 request的线程连接已经释放了 logger.info("线程:" + Thread.currentThread().getName()); } }注意:异步请求时,可以利用ThreadPoolExecutor自定义个线程池使用过滤器时,需要加入asyncSupported为true配置,开启异步请求支持@WebServlet(urlPatterns = "/okong", asyncSupported = true ) public class AsyncServlet extends HttpServlet ...
2019年07月28日
1,343 阅读
0 评论
0 点赞
2019-07-28
Spring Boot自定义启动Banner
看烦了自带的Banner,动手修改一个属于自己的Banner,提现逼格的时候到了~哈哈,以下是官网给的配置指南:文字形式其实,替换很简单,只需要在classpath路径下创建一个banner.txt即可。具体的一些变量官网也有给出,具体如下:${AnsiColor.BRIGHT_YELLOW} //////////////////////////////////////////////////////////////////// // _ooOoo_ // // o8888888o // // 88" . "88 // // (| ^_^ |) // // O\ = /O // // ____/`---'\____ // // .' \\| |// `. // // / \\||| : |||// \ // // / _||||| -:- |||||- \ // // | | \\\ - /// | | // // | \_| ''\---/'' | | // // \ .-\__ `-` ___/-. / // // ___`. .' /--.--\ `. . ___ // // ."" '< `.___\_<|>_/___.' >'"". // // | | : `- \`.;`\ _ /`;.`/ - ` : | | // // \ \ `-. \_ __\ /__ _/ .-` / / // // ========`-.____`-.___\_____/___.-`____.-'======== // // `=---=' // // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // // 佛祖保佑 永不宕机 永无BUG // //////////////////////////////////////////////////////////////////// 关闭banner如果需要关闭banner,可以通过设置SpringApplicationBuilder来设置bannerMode为OFF。 SpringApplicationBuilder builder = new SpringApplicationBuilder(DemoApplication.class); builder.bannerMode(Banner.Mode.OFF); builder.run(args);
2019年07月28日
1,222 阅读
0 评论
1 点赞
2019-07-28
Spring Boot热部署
但当服务功能一多,启动速度缓慢时,还是配置个热部署比较方便。在SpringBoot中,只需要加入一个spring-boot-devtools即可。<!-- 增加热部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>若不生效,可试着在打包工具spring-boot-maven-plugin下的configuration加入true看看,具体配置项如下:<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
2019年07月28日
1,420 阅读
0 评论
0 点赞
2019-07-28
Spring Boot配置跨域
同源策略很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略。同源策略是由Netscape提出的一个著名的安全策略,它是浏览器最核心也最基本的安全功能,现在所有支持JavaScript的浏览器都会使用这个策略。所谓同源是指协议、域名以及端口要相同。同源策略是基于安全方面的考虑提出来的,这个策略本身没问题,但是我们在实际开发中,由于各种原因又经常有跨域的需求,传统的跨域方案是JSONP,JSONP虽然能解决跨域但是有一个很大的局限性,那就是只支持GET请求,不支持其他类型的请求,而今天我们说的CORS(跨域源资源共享)(CORS,Cross-origin resource sharing)是一个W3C标准,它是一份浏览器技术的规范,提供了Web服务从不同网域传来沙盒脚本的方法,以避开浏览器的同源策略,这是JSONP模式的现代版。在Spring框架中,对于CORS也提供了相应的解决方案,今天我们就来看看SpringBoot中如何实现CORS。前端请求<!DOCTYPE html> <html> <head> <title>Welcome to nginx!</title> <script src="jquery.min.js"></script> </head> <body> <div id="myDiv"></div> <script> $(document).ready(function () { $.ajax({ url: "http://localhost:8080/CrossOrigin", type:"post", async: false, success:function(data){ $("#myDiv").html(data); } }); }); </script> </body> </html>配置后端/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") public String crossOrigin(){ return "crossOrigin"; } }打开前端页面,我们可以看一下,报错信息如下,也就是出现了跨域通过CrossOrigin配置跨域我们可以将@CrossOrigin注解到方法上,实现跨域请求,我们对后端方法改造如下:/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") @CrossOrigin(origins = "http://localhost:1234") public String crossOrigin(){ return "crossOrigin"; } }通过CorsFilter配置跨域继续后端改造修改yaml文件,增加跨域配置信息#配置跨域 cors: allowedOrigin: - http://localhost:1234 allowCredentials: - true allowMethods: - GET - POST - PUT - DELETE maxAge: 7200 path: /** 增加CrosFilter配置文件package cc.lisen.cors.config; import lombok.Getter; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import java.util.List; /** * 跨域配置 * * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @Configuration @ConfigurationProperties(prefix = "cors") @Getter @Setter public class CorsFilterConfig { private boolean allowCredentials; private List<String> allowedOrigin; private List<String> allowMethods; private long maxAge; private String path; /** * 配置跨域 * * @return CorsFilter */ @Bean public CorsFilter corsFilter() { CorsConfiguration corsConfiguration = new CorsConfiguration(); this.allowedOrigin.forEach(corsConfiguration::addAllowedOrigin); this.allowMethods.forEach(corsConfiguration::addAllowedMethod); corsConfiguration.setAllowCredentials(this.allowCredentials); corsConfiguration.setMaxAge(this.maxAge); UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource(); urlBasedCorsConfigurationSource.registerCorsConfiguration(this.path, corsConfiguration); return new CorsFilter(urlBasedCorsConfigurationSource); } } 增加请求/** * @author laughing * @date 2020/9/26 * @site https://lisen.cc */ @RestController public class CorsController { /** * 方法配置跨域 * @return String */ @RequestMapping("/CrossOrigin") // @CrossOrigin(origins = "http://localhost:1234") public String crossOrigin(){ return "crossOrigin"; } }再次请求,可以发现仍然能够正常访问通过WebMvcConfigurer配置跨域@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/cors/**") .allowedHeaders("*") .allowedMethods("*") .maxAge(1800) .allowedOrigins("http://localhost:8081"); } }
2019年07月28日
1,206 阅读
0 评论
0 点赞
1
...
7
8
9