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

1.异步任务
在一次请求中,可能会调用一个耗时很长的方法;
如果用普通的同步方式来处理,必须等到方法执行完才能得到响应;
有时需要请求后立即得到响应,并且将耗时的操作异步来处理;
可以通过启一个线程专门用来做异步操作;
在Spring 3.x之后提供了@Async用来处理异步任务;
 
开启异步任务:
    在工程的启动类上加注解
@EnableAsync
 
业务类:
    给需要异步操作的方法加上注解@Async
@Service
public class AsyncService {
 
    //@Async表示该方法是一个异步方法
    @Async
    public void go(){
        try {
            Thread.sleep(3000);     //等待3秒,模拟耗时操作
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理完成");
    }
}
 
controller:
@RestController
public class HelloController {
    @Autowired
    private AsyncService asyncService;
 
    @GetMapping("/async")
    public String go(){
        asyncService.go();
        return "hello world";
    }
}
 
测试:
    请求/async接口,会立即返回“hello world”;3秒后控制台打印“处理完成”;
 
2.定时任务
项目开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。
Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、 TaskScheduler 接口。
 
主要步骤:
    1】在启动类中加上注解 @EnableScheduling 开启定时任务;
    2】在需要定时执行的方法上加上注解  @Scheduled;
    3】 使用cron表达式配置如何定时执行
 
cron表达式:
符号的含义:
 
corn表达式实例:
 
测试:
启动类上加注解:
@EnableScheduling
 
业务类:
@Service
public class ScheduleService {
    /**
     * 秒 分 时 日 月 周几
     */
    @Scheduled(cron = "0 * * * * MON-FRI")
    public void sayHello(){
        System.out.println("hello world");     //周一到周五每分钟在控制台打印一次“hello world”
    }
}
 
结果:
    不需要调用业务类的方法;
    每到第0秒时,控制台会输出一次;
 
3.邮件任务
springboot使用邮件任务的步骤:
    • 邮件发送需要引入spring-boot-starter-mail
    • Spring Boot 自动配置MailSenderAutoConfiguration
    • 定义MailProperties内容,配置在application.yml中
    • 自动装配JavaMailSender
    • 测试邮件发送
 
以qq邮箱为例;
1)开启服务,获取授权码
授权码:
 xxxxxxxxxxxxxxxxx
 
2)yml配置
spring:
  mail:
    host: smtp.qq.com
    username: 717416153@qq.com
    password: xxxxxxxxxxxxxxxxx
 
 
3)junit测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailTest {
    @Autowired
    private JavaMailSender sender;
 
    //简单邮件
    @Test
    public void sendMail(){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("京东168活动");  //邮件标题
        message.setText("什么都没有~");      //邮件内容
        message.setTo("[email protected]");    //给谁发
        message.setFrom("[email protected]");        //谁发的
        sender.send(message);
    }
 
    //复杂邮件
    @Test
    public void sendMali2() throws Exception{
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);    //参数2:是否带附件
        helper.setSubject("京东168活动");  //邮件标题
        helper.setText("<b style='color:red'>什么都没有~</b>", true);      //邮件内容;参数2:是否解析html标签
        helper.setTo("[email protected]");    //给谁发
        helper.setFrom("[email protected]");        //谁发的
 
        //附件
        helper.addAttachment("1.jpg", new File("D:\\zgcf.jpg"));
        helper.addAttachment("2.jpg", new File("D:\\wst.jpg"));
 
        sender.send(message);
    }
}
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/ShiningArmor/p/13161267.html