SpringBoot整合Async


title:SpringBoot整合Async,Scheduled
time: 2019年8月25日11:23:53
tags:Async


SpringBoot整合Async

  • 在要开启异步的方法前加入@Async

    @Service
    public class AsyncService {
    
        @Async
        public void testAsync() throws InterruptedException {
    
            Thread.sleep(5000);
            //默认是先执行,休眠操作,再执行下面的打印操作
            //开启异步后,可以在休眠时,阻塞时,进行下个操作的进行。
            System.out.println("插入数据中、、、、");
    
        }
    
    }
    
  • 并在application类前加入@EnableAsync

    @SpringBootApplication
    @EnableAsync
    public class AsyncApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AsyncApplication.class, args);
        }
    
    }
    
  • 测试

    @RestController
    public class HelloController {
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String  hello() throws InterruptedException {
            asyncService.testAsync();
            return "success";
        }
    }
    
    

SpringBoot整合Scheduled

  • 在你要加入定时任务方法的前面添加@Scheduled注解

    @Service
    public class ScheduledService {
        /* corn()参数
         second ,minute, hour, day of month, month ,day of week.
        * "0 * * * * MON-FRI" 表示周一到周五每月每天每小时每分钟的0秒执行
        *   中间用空格分开
        * */
        //表示周一到周六每一分钟的前4秒执行
        @Scheduled(cron = "0-4 * * * * MON-SAT")
        public String  hello() {
            String x = "一分钟过去了,你这一分钟做了些什么,学到了什么东西";
            System.out.println(x);
            return x;
        }
    }
    
    
  • 并在application类前加入@EnableScheduling

    @SpringBootApplication
    @EnableAsync
    @EnableScheduling
    public class AsyncApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(AsyncApplication.class, args);
        }
    
    }
    
  • 测试

    @RestController
    public class AsyncController {
        @Autowired
        AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String  hello() throws InterruptedException {
            asyncService.testAsync();
            return "success";
        }
    }
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值