任务
和==多线程==有关
异步任务
@Servicepublic class AsynService {public void hello() {try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("数据正在处理...");}}
同时
@RestControllerpublic class AsynController {@Autowiredprivate AsynService asynService;@RequestMapping("/hello")public String hello() {asynService.hello(); // 会停止三秒,转圈return "ok";}}
那么用户体验就是十分的差
只需要
在对应的异步方法加上注解
@Servicepublic class AsynService {// 告诉Spring 这是一个异步方法@Asyncpublic void hello() {try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("数据正在处理...");}}
同时
启动类 开启异步注解
@EnableAsync // 开启异步注解
邮件发送
1、导入依赖
<!-- javax.mail --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>
2、开启并导入POP3/SMTP服务创建的授权码
spring.mail.username=1412148742@qq.comspring.mail.password=(开启POP3/SMTP服务创建的授权码)spring.mail.host=smtp.qq.com# 加密验证(QQ邮箱特有,其他不需要)spring.mail.properties.mail.smtp.ssl.enable=true
3、进行测试
@AutowiredJavaMailSenderImpl mailSender;@Testvoid contextLoads() {// 一个简单的邮件SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setSubject("这是主题");mailMessage.setText("这个文本内容");mailMessage.setTo("dafran@yeah.net");mailMessage.setFrom("1412148742@qq.com");mailSender.send(mailMessage);}@Testvoid contextLoads2() throws MessagingException {// 一个复杂的邮件MimeMessage mimeMessage = mailSender.createMimeMessage();// 组装MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);helper.setSubject("这是主题plus");helper.setText("<p style='color:red'>这个文本内容plus</p>",true);// 附件helper.addAttachment("1.jpg",new File("F:\\Pictures\\1.png"));helper.addAttachment("2.jpg",new File("F:\\Pictures\\1.png"));helper.setTo("dafran@yeah.net");helper.setFrom("1412148742@qq.com");mailSender.send(mimeMessage);}
可以作为工具类进行封装
定时任务
TaskScheduler // 任务调度器TaskExecutor // 任务执行者@EnableScheduling // 开启定时任务功能的注解@Scheduled // 什么时候执行Cron表达式
1、启动类开启
@EnableScheduling // 开启定时任务功能的注解
2、对应方法开启
@Servicepublic class ScheduledService {// cron表达式// 秒、分、时、日、月、周几@Scheduled(cron = "0 * * * * 0-7")public void hello() {System.out.println("hello,被执行");}}
