1. 应用场景:
单体应用(并发少、就公司内部使用)、业务比较简单、单一、稳定,传统行业首选,项目初期。
2. 主要方式:
- Spring XML配置方式,timer。
<bean id="cycleBonusTimer" class="cn.edu.wx.distribution.timer.CycleBonusTimer"></bean>
<!-- 定时器相关,用于发放奖金 -->
<task:scheduled-tasks>
<task:scheduled ref="cycleBonusTimer" method="run" cron="0 0/1 * * * ?"/>
</task:scheduled-tasks>
public class CycleBonusTimer {
public void run(){
//业务
}
}
- Spring 注解方式,@Scheduled。
@Component
public class Scheduler {
@Scheduled(cron = "0 30 0 * * *")
public void profitComputeTask() {
logger.info("======================================start profitComputeTask======================================");
taskService.handleProfitCompute();
logger.info("======================================end profitComputeTask======================================");
}
}
- Spring 异步利用多线程处理,@Async。
@Component
public class TestAsyncBean {
@Async
public void sayHello3() throws InterruptedException {
Thread.sleep(2 * 1000);//网络连接中 。。。消息发送中。。。
System.out.println("我爱你啊!");
}
}
3. 总结:
从XML到注解,在从注解到异步处理,配置使用方式越来越简单,性能越来越好;但同时暴露了这三种方式缺点:
- 扩展性不高(每次业务迭代都需要修改应用代码)
- 性能也受单机资源的限制、
- 代码侵入性太高
- 方式单一
- 没监控(调度是否成功只能通过数据或LOG来定位)、没通知提醒(Email)
- 单机容错率低
- .....