SpringBoot如何实现异步、定时任务?

写在前面:2020年面试必备的Java后端进阶面试题总结了一份复习指南在Github上,内容详细,图文并茂,有需要学习的朋友可以Star一下!
GitHub地址:https://github.com/abel-max/Java-Study-Note/tree/master

(一)异步任务
异步任务的需求在实际开发场景中经常遇到,Java实现异步的方式有很多,比如多线程实现异步。在SpringBoot中,实现异步任务只需要增加两个注解就可以实现。当前类添加@Async注解,启动类添加@EnableAsync

编写一个service,AsynService,让这个服务暂停3秒后再输出数据

@Service
public class AsynService {
    @Async
    public void async(){
        try {
            Thread.sleep(3000);
            System.out.println("执行结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

编写controller,调用这个服务类

@RestController
public class IndexController {
    @Autowired
    public AsynService asynService;
    @RequestMapping("/index")
    public String  asynctask(){
        asynService.async();
        return "async task";
    }
}

运行后在浏览器中访问http://localhost:8080/index ,会发现由于开启了异步,浏览器中会先输出async task,过了三秒后控制台才会输出执行结束。

(二)定时任务
我在之前的秒杀开源项目中已经使用过定时任务,当时的场景时,每隔1分钟去轮询数据库查询过期的商品。定时任务的应用范围很广,比如每天12点自动打包日志,每天晚上12点备份等等。 在SpringBoot实现定时任务也只需要两个注解:@Scheduled和@EnableScheduling 和前面一样,@Scheduled用在需要定时执行的任务上,@EnableScheduling用在启动类上。 首先来编写定时任务类:

@Service
public class ScheduleService {

    @Scheduled(cron = "0/10 * * * * ? ")
    public void sayHello(){
        System.out.println("hello");
    }
}

@Scheduled注解中需要加入cron表达式,用来判断定时任务的执行时间,这里表示每10秒执行一次。

然后在启动类中加上注解@EnableScheduling。 运行项目,会发现每隔十秒会输出一条hello。

猜你喜欢

转载自blog.csdn.net/qwe123147369/article/details/109180522
今日推荐