SpringBoot(十三)异步、定时、邮件任务

异步任务
1、创建一个service包

2、创建一个类AsyncService

异步处理还是非常常用的,比如我们在网站上发送邮件,后台会去发送邮件,此时前台会造成响应不动,直到邮件发送完毕,响应才会成功,所以我们一般会采用多线程的方式去处理这些任务。

编写方法,假装正在处理数据,使用线程设置一些延时,模拟同步等待的情况;

@Service
public class AsyncService {

   public void hello(){
       try {
           Thread.sleep(3000);
      } catch (InterruptedException e) {
           e.printStackTrace();
      }
       System.out.println("业务进行中....");
  }
}

3、编写controller包

4、编写AsyncController类

我们去写一个Controller测试一下

@RestController
public class AsyncController {

@Autowired
AsyncService asyncService;

@GetMapping("/hello")
public String hello(){
asyncService.hello();
return “success”;
}

}
5、访问http://localhost:8080/hello进行测试,3秒后出现success,这是同步等待的情况。

问题:我们如果想让用户直接得到消息,就在后台使用多线程的方式进行处理即可,但是每次都需要自己手动去编写多线程的实现的话,太麻烦了,我们只需要用一个简单的办法,在我们的方法上加一个简单的注解即可,如下:

6、给hello方法添加@Async注解;

//告诉Spring这是一个异步方法
@Async
public void hello(){
   try {
       Thread.sleep(3000);
  } catch (InterruptedException e) {
       e.printStackTrace();
  }
   System.out.println("业务进行中....");
}

SpringBoot就会自己开一个线程池,进行调用!但是要让这个注解生效,我们还需要在主程序上添加一个注解@EnableAsync ,开启异步注解功能;

@EnableAsync //开启异步注解功能
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

7、重启测试,网页瞬间响应,后台代码依旧执行!

邮件任务
邮件发送,在我们的日常开发中,也非常的多,Springboot也帮我们做了支持

邮件发送需要引入spring-boot-start-mail

SpringBoot 自动配置MailSenderAutoConfiguration

定义MailProperties内容,配置在application.yml中

自动装配JavaMailSender

测试邮件发送
1、引入pom依赖

org.springframework.boot spring-boot-starter-mail 看它引入的依赖,可以看到 jakarta.mail com.sun.mail jakarta.mail 1.6.4 compile 2、查看自动配置类:MailSenderAutoConfiguration

这个类中存在bean,JavaMailSenderImpl
然后我们去看下配置文件

@ConfigurationProperties(
   prefix = "spring.mail"
)
public class MailProperties {
   private static final Charset DEFAULT_CHARSET;
   private String host;
   private Integer port;
   private String username;
   private String password;
   private String protocol = "smtp";
   private Charset defaultEncoding;
   private Map<String, String> properties;
   private String jndiName;
}

3、配置文件:

spring.mail.username=24736743@qq.com
spring.mail.password=你的qq授权码
spring.mail.host=smtp.qq.com

  • qq需要配置ssl
    spring.mail.properties.mail.smtp.ssl.enable=true
    获取授权码:在QQ邮箱中的设置->账户->开启pop3和smtp服务

4、Spring单元测试

@Autowired
JavaMailSenderImpl mailSender;

@Test
public void contextLoads() {
   //邮件设置1:一个简单的邮件
   SimpleMailMessage message = new SimpleMailMessage();
   message.setSubject("通知-明天来狂神这听课");
   message.setText("今晚7:30开会");

   message.setTo("24736743@qq.com");
   message.setFrom("24736743@qq.com");
   mailSender.send(message);
}

@Test
public void contextLoads2() throws MessagingException {
   //邮件设置2:一个复杂的邮件
   MimeMessage mimeMessage = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

   helper.setSubject("通知-明天来狂神这听课");
   helper.setText("<b style='color:red'>今天 7:30来开会</b>",true);

   //发送附件
   helper.addAttachment("1.jpg",new File(""));
   helper.addAttachment("2.jpg",new File(""));

   helper.setTo("24736743@qq.com");
   helper.setFrom("24736743@qq.com");

   mailSender.send(mimeMessage);
}

查看邮箱,邮件接收成功!

定时任务

Spring为我们提供了异步执行任务调度的方式,提供了两个接口。
TaskExecutor接口
TaskScheduler接口

1.创建一个ScheduledService

@Service
public class ScheduledService {

    //秒   分   时     日   月   周几
    //注意cron表达式的用法;
    @Scheduled(cron = "50 31 11 * * ?")
    public void hello(){
        System.out.println("hello,luo");
    }
}

2、这里写完定时任务之后,我们需要在主程序上增加@EnableScheduling 开启定时任务功能

@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class SpringbootTaskApplication {

   public static void main(String[] args) {
       SpringApplication.run(SpringbootTaskApplication.class, args);
  }

}

其中问号(?)只能用在DayofMonth和DayofWeek两个域,由于指定日期(DayofMonth)和指定星期(DayofWeek)存在冲突,所以当指定了日期(DayofMonth)后(包括每天*),星期(DayofWeek)必须使用问号(?),同理,指定星期(DayofWeek)后,日期(DayofMonth)必须使用问号(?)。

0 0/10 * * * 与 0 */10 * * * 的差别在于什么地方。
在说这两者的差别之前,先说下各个字符代表的含义。0代表从0分开始,*代表任意字符,/代表递增。
也就是说0 0/10 * * *代表从0分钟开始,每10分钟执行任务一次。0 */10 * * *代表从任务启动开始每10分钟执行任务一次。有人会问,这不是一样的么?
答案是不一样的。因为起始的时间不一样。例如:从5:07分钟的时候执行该任务第一种写法会在5:10的时候进行执行,写法二会在5:17进行执行。这就是两者的差别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值