springboot 异步执行
一般项目中会有很多需要异步执行的工作,比如发消息等
项目启动类添加@EnableAsync 注解,如
@SpringBootApplication(scanBasePackages = {"扫描的包"})
@EnableAsync
@EnableRetry
public class ZmallApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ZmallApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(ZmallApplication.class, args);
}
}
发送消息
1 @Service 2 @EnableScheduling 3 public class AppointmentServiceImpl implements AppointmentService{ 4 private Logger logger = LoggerFactory.getLogger(AppointmentServiceImpl.class); 5 private ConcurrentLinkedQueue<AppointmentDto> appointQueue = new ConcurrentLinkedQueue<>(); 6 7 @Autowired 8 private AppointmentRepository appointmentRepository; 9 10 @Autowired 11 private ApplicationContext applicationContext; 12 13 public ServiceResult addAppointmen(String mobile,String type) { 14 AppointmentDto a = new AppointmentDto(); 15 a.setMobile(mobile); 16 a.setAppointmentType(type); 17 a.setZestUid(CookieUtils.getUserId()); 18 appointQueue.offer(a); 19 return ServiceResultFactory.getServiceResult(ResultMessage.Code.SUCCESS, "预约成功", null,0); 20 } 21 22 public void remindUser(String type) { 23 List<AppointmentDto> appoints = appointmentRepository.getNeedRemindUser(type); 24 logger.info("预约提醒开始执行,本次需提醒:{}",appoints.size()); 25 if(appoints.size()>0){ 26 AppointmentEvent evt = new AppointmentEvent(); 27 evt.setAppointments(appoints); 28 applicationContext.publishEvent(evt); 29 } 30 } 31 32 void asyncSaveAppointmenToDB(){ 33 List<AppointmentDto> mobiles = new ArrayList<>(); 34 AppointmentDto a = null; 35 int count = 0; 36 while ((a = appointQueue.poll()) != null) { 37 mobiles.add(a); 38 count++; 39 if (count >= 5) { 40 appointmentRepository.addAppointmen(mobiles); 41 count = 0; 42 } 43 } 44 if (count > 0) { 45 appointmentRepository.addAppointmen(mobiles); 46 count = 0; 47 } 48 } 49 50 @Scheduled(cron = "0/20 * * * * ?") 51 public void saveAppointmenTask() throws Exception { 52 logger.info("用户预约执行"); 53 asyncSaveAppointmenToDB(); 54 } 55 56 public ServiceResult addAppointmen(AppointmentDto appointProduct) { 57 logger.info("优惠促销提醒的折扣商品是:{}",appointProduct); 58 appointQueue.offer(appointProduct); 59 return ServiceResultFactory.getServiceResult(ResultMessage.Code.SUCCESS, "预约成功", null,0); 60 } 61 }
异步事件监听,可以有多个,主要根据参数类型来区分
@Async @Component public class HandleAsyncEventListener { 。。。 @EventListener public void handleRemindUserEvent(AppointmentEvent evt) { List<AppointmentDto> appointments = evt.getAppointments(); long start = System.currentTimeMillis(); logger.info("预约提醒发短信开始执行"); String smsTemplate = smsRepository .getSmsTemplateByCode(CommonParams.APPOINTMENT_REMIND_SMS_TEMP); for (AppointmentDto dto : appointments) { logger.info("预约提醒发短信,手机号:{}", dto.getMobile()); smsService.asyncSendSms(smsTemplate, dto.getAppointmentType(), dto.getMobile()); logger.info("预约提醒发短信,手机号:{}", dto.getMobile()); } long end = System.currentTimeMillis(); logger.info("预约提醒发短信结束,本次调用共耗时:{}", (end - start)); int cnt = appointmentRepository.updateAppointmenState(appointments); logger.info("数据量:{}", cnt); } }
浙公网安备 33010602011771号