Springboot几种任务的整合方法
这篇文章主要介绍了Springboot几种任务的整合方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一异步任务
启动类
@MapperScan("com.topcheer.*.*.dao")
@SpringBootApplication
@EnableCaching
@EnableRabbit
@EnableAsync
publicclassOss6Application{
publicstaticvoidmain(String[]args){
SpringApplication.run(Oss6Application.class,args);
}
}
Controller层
/**
*@authorWGR
*@create2019/10/12--21:53
*/
@RestController
publicclassAsynController{
@Autowired
AsynServiceasyncService;
@GetMapping("/hello")
publicStringhello(){
asyncService.hello();
return"success";
}
}
Service层
/**
*@authorWGR
*@create2019/10/12--21:52
*/
@Service
publicclassAsynService{
//告诉Spring这是一个异步方法
@Async
publicvoidhello(){
try{
Thread.sleep(3000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
测试结果:
页面直接显示success,控制台过3秒显示处理数据中...
二定时任务
此处的定时,标注在方法上+注解,假如想修改生成环境的时间,不是很灵活,后面补充Quartz+boot,采用数据库配置和反射的原理。
注:java的cron表达式和Linux的不太一样,请注意,java为6位,linux为5位。
启动类
@SpringBootApplication
@EnableScheduling
publicclassOss6Application{
publicstaticvoidmain(String[]args){
SpringApplication.run(Oss6Application.class,args);
}
}
服务类
@Service
publicclassScheduledService{
/**
*second(秒),minute(分),hour(时),dayofmonth(日),month(月),dayofweek(周几).
*0****MON-FRI
*【00/514,18**?】每天14点整,和18点整,每隔5分钟执行一次
*【01510?*1-6】每个月的周一至周六10:15分执行一次
*【002?*6L】每个月的最后一个周六凌晨2点执行一次
*【002LW*?】每个月的最后一个工作日凌晨2点执行一次
*【002-4?*1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
*/
//@Scheduled(cron="0****MON-SAT")
//@Scheduled(cron="0,1,2,3,4****MON-SAT")
//@Scheduled(cron="0-4****MON-SAT")
@Scheduled(cron="0/4****MON-SAT")//每4秒执行一次
publicvoidhello(){
System.out.println("hello...");
}
}
三邮件任务
pom.xml
org.springframework.boot spring-boot-starter-mail test
配置文件
spring: mail: username:*********** password:*********(这是qq邮箱的授权码) host:smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=true
测试类
@Autowired(required=false)
JavaMailSenderImplmailSender;
@Test
publicvoidcontextLoads(){
SimpleMailMessagemessage=newSimpleMailMessage();
//邮件设置
message.setSubject("通知-今晚开会");
message.setText("今晚7:30开会");
message.setTo("**************");
message.setFrom("**************");
mailSender.send(message);
}
@Test
publicvoidtest02()throwsException{
//1、创建一个复杂的消息邮件
MimeMessagemimeMessage=mailSender.createMimeMessage();
MimeMessageHelperhelper=newMimeMessageHelper(mimeMessage,true);
//邮件设置
helper.setSubject("测试");
helper.setText("今天7:30开会",true);
helper.setTo("***************");
helper.setFrom("**************");
//上传文件
helper.addAttachment("nginx.md",newFile("C:\\Users\\asus\\Desktop\\nginx.md"));
mailSender.send(mimeMessage);
}
结果:
总结
简单的介绍了几个任务,后面有时间会详细说明在项目实战的开发应用。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。