Spring Boot 12. 与任务

异步任务、定时任务、邮件任务

一、异步任务

  • 在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。
  • 两个注解:
    @EnableAysnc@Aysnc
  • 创建一个普通的 springboot项目进行测试
    @Service
    public class AsyncService {
    
        //告诉 spring这是一个异步方法,还需要在启动类上开启 @EnableAsync(开启异步注解)
        @Async
        public void hello() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("处理数据中");
        }
    }
    
    @RestController
    public class AsyncController {
        @Autowired
        AsyncService asyncService;
    
        @GetMapping("/hello")
        public String hello() {
            asyncService.hello();
            return "hello word";
        }
    }
    
  • 开需要在启动类上开启异步注解@EnableAsync

二、定时任务

  • 项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。
  • 两个注解:@EnableScheduling@Scheduled
  • cron表达式
    image
    image
  • 在启动类上使用,@EnableScheduling:开启基于注解的定时任务
@Service
public class ScheduledService {
    /**
     * 想要定时任务生效还需要在启动类上加注解 @EnableScheduling 
     * second,minute,hour,day of month,month,day fo week
     * 秒 分 时 日 月 周
     * 0/5 * * * * ? 每五秒执行一次
     */
    //@Scheduled(cron = "0/5 * * * *  ?")//每五秒执行一次
    //@Scheduled(cron = "0,1,2,4,5 * * * * MON-FRI")//周一到周五 1-5秒都会启动
    //@Scheduled(cron = "0-5 * * * * MON-FRI")//周一到周五 1-5秒都会启动
    @Scheduled(cron = "0/5 * * * * MON-FRI")//周一到周五 每5秒都会启动
    public void hello() {
        System.out.println("你好,我被执行了");
    }
}

三、邮件任务

  1. 邮件发送需要引入spring-boot-starter-mail
  2. Spring Boot 自动配置MailSenderAutoConfiguration
  3. 定义MailProperties内容,配置在application.yml中
  4. 自动装配JavaMailSender
  5. 测试邮件发送
    image
<!--邮件发送-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
#这里以qq邮箱为例
# qq邮箱服务器
spring.mail.host=smtp.qq.com
# 你的qq邮箱账户
spring.mail.username=xxx@qq.com
# 你的qq邮箱第三方授权码
spring.mail.password=xxx
# 编码类型
spring.mail.default-encoding=UTF-8
# 530报错需要开启 ssl 开启
#spring.mail.properties.mail.smtp.ssl.enable=true
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringApplicationTaskTest {
    @Autowired
    JavaMailSender mailSender;

    //发送普通邮件
    @Test
    public void testSendEmail() {
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件设置
        message.setSubject(LocalDateTime.now().toString());//标题
        message.setText("i have girl for you");//内容
        message.setTo("2511862286@qq.com");//发给谁
        message.setFrom("2441972742@qq.com");//邮件是谁发的
        mailSender.send(message);
    }

    //发送附件的邮件
    @Test
    public void testSendEmail2() throws Exception {
        //1. 创建一个复杂的消息邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        //邮件设置
        helper.setSubject(LocalDateTime.now().toString());//标题
        helper.setText("<b style='color:pink'>i have girl for you</b>", true);//内容 true代表支持html
        helper.setTo("2511862286@qq.com");//发给谁
        helper.setFrom("2441972742@qq.com");//邮件是谁发的
        //上传文件
        String path = "C:\\Users\\KAlways18\\Downloads\\ing\\94850870_p0_master1200.jpg";
        FileSystemResource file = new FileSystemResource(new File(path));
        helper.addAttachment("filename.jpeg", file);
        mailSender.send(mimeMessage);
    }
}
原文地址:https://www.cnblogs.com/zk2020/p/15755953.html