springboot11-任务

异步任务

  1. 在Java应用中, 大多数情况都是通过同步的方式来实现交互处理的, 但是在处理与第三方系统交互的时候, 容易造成响应迟缓的情况,
  2. 之前大部分都是使用多线程来完成此类任务, 其实, 在Spring 3.x之后, 就内置了@Async来解决该问题.
    • 在主启动类上加@EnableAysnc开启异步处理功能
    • 在需要异步处理的方法/类上加@Async
  3. 举例
    • 主启动类
      @EnableAsync //开启异步注解功能
      @SpringBootApplication
      public class Springboot04TaskApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(Springboot04TaskApplication.class, args);
          }
      
      }
    • service方法
      @Service
      public class AsyncService {
      
          //告诉Spring这是一个异步方法
          @Async
          public void hello() {
              try {
                  Thread.sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              System.out.println("处理数据中...");
          }
      }
    • controller方法
      @RestController
      public class AsyncController {
      
          @Autowired
          private AsyncService asyncService;
      
          @GetMapping("/hello")
          public String hello() {
              asyncService.hello();
              return "success";
          }
      }

定时任务

  1. 项目开发中经常需要执行一些定时任务, 比如需要在每天凌晨时候, 分析一次前一天的日志信息.
  2. Spring为我们提供了@EnableScheduling(开启定时任务), @Scheduled(加在要定时执行的方法上)
    • cron表达式
  3. 举例
    • 主启动类
      @EnableScheduling //开启基于注解的定时任务.
      @SpringBootApplication
      public class Springboot04TaskApplication {
      
          public static void main(String[] args) {
              SpringApplication.run(Springboot04TaskApplication.class, args);
          }
      
      }
    • service方法
      @Service
      public class ScheduledService {
      
          /**
           * cron属性: 定时表达式
           *  second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
           *      【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
           *      【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
           *      【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
           *      【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
           *      【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
           */
      //    @Scheduled(cron = "0 * * * * MON-FRI")
      //    @Scheduled(cron = "0,1,2,3,4 * * * * MON-FRI") 枚举
      //    @Scheduled(cron = "0-4 * * * * MON-FRI") 区间
          @Scheduled(cron = "0/4 * * * * MON-FRI") //步长 从0秒开始, 每四秒执行一次
          public void hello() {
              System.out.println("hello...");
          }
      }

邮件任务

  1. 邮件发送需要引入spring-boot-starter-mail依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
  2. 邮件发送的流程
  3. SpringBoot会自动装配MailSenderAutoConfiguration
    • 所以我们只需要在application.properties中进行相关配置即可.
      spring.mail.username=123456789@qq.com
      #注意这里不是邮箱的密码, 而是第三方登录的授权码(这里用smtp )
      spring.mail.password=uoipasjghgqwetrh
      spring.mail.host=smtp.qq.com
      spring.mail.properties.mail.smtp.ssl.enable=true
  4. 邮件发送需要自动装配JavaMailSender
  5. 简单邮件的发送
    • 需使用SimpleMailMessage();
      @RunWith(SpringRunner.class)
      @SpringBootTest
      public class Springboot04TaskApplicationTests {
      
          @Autowired
          private JavaMailSenderImpl mailSender;
      
          @Test
          public void contextLoads() {
              SimpleMailMessage message = new SimpleMailMessage();
              //邮件设置
              //设置标题
              message.setSubject("Hello");
              //设置内容
              message.setText("hello world");
              //要发给谁
              message.setTo("987654321@qq.com");
              //署名
              message.setFrom("123456789@qq.com");
              for(int i = 0; i < 30000; i++) {
                  mailSender.send(message);
              }
          }
      }
  6. 复杂邮件的发送(如带附件, html样式等)
        @Autowired
        private JavaMailSenderImpl mailSender;
    
        @Test
        public void test02() throws MessagingException {
            //1.创建一个复杂的消息邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
    
            //multipart: 设置为true表示将要上传文件
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    
            helper.setSubject("通知今晚开会");
            //可以添加html和css样式, 需要把html属性设置为true.
            helper.setText("<b style='color:red'>今天不开会了</b>", true);
    
            helper.setTo("2222222222@163.com");
            helper.setFrom("1111111115@qq.com");
    
            //上传附件
            helper.addAttachment("1.jpg", new File("C:\\1.jpg"));
            helper.addAttachment("2.jpg", new File("C:\\2.jpg"));
            mailSender.send(mimeMessage);
    }
posted @ 2020-06-18 16:49  yellowstreak  阅读(121)  评论(0编辑  收藏  举报