Spring Boot(十六)--------异步任务、邮件发送、定时任务

Spring Boot(十六)--------异步任务、邮件发送、定时任务

26、异步任务

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

  • 创建一个Service包,新建AsyncService类,编写方法,模拟处理数据时的等待情况

@Service
public class AsyncService {
    public void hello(){

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据处理ing....");
    }
}
  • 创建controller包,新建AsyncController类,测试刚刚的方法
@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;
    @RequestMapping("/hello")
    public String hello(){
        //停止三秒
        asyncService.hello();
        return "ok";
    }
}
  • 测试,发现访问时,等待了3秒才显示了ok字样,这就是同步等待的表现,用户体验不好,该如何解决
  • hello()具体方法上添加注解@Async
@Service
public class AsyncService {
    //告诉Spring这是一个异步方法
    @Async
    public void hello(){

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据处理ing....");
    }
}

  • 在主程序上添加注解@EnableAsync,开启异步注解功能
//开启异步注解功能
@SpringBootApplication
@EnableAsync
public class Springboot09TestApplication {

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

}
  • 测试,网页瞬间响应,显示ok字样,控制台3秒后输出“数据处理ing”

27、邮件任务

  • 邮件发送,在我们的日常开发中非常多

  • 需要引入spring-boot-start-mail依赖;SpringBoot 自动配置MailSenderAutoConfiguration;定义MailProperties内容,配置在application.properties中;自动装配JavaMailSender

  • 导入pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
  • 查看配置文件MailProperties
@ConfigurationProperties(prefix = "spring.mail")
public class MailProperties {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
	private String host;
	private Integer port;
	private String username;
	private String password;
	private String protocol = "smtp";
	private Charset defaultEncoding = DEFAULT_CHARSET;
	private Map<String, String> properties = new HashMap<>();
	private String jndiName;
	...
}
  • 编写配置文件application.properties
spring.mail.username=邮箱账户
spring.mail.password=邮箱授权码
# 发送的服务器
spring.mail.host=smtp.qq.com
# qq需要开启授权验证 配置ssl
spring.mail.properties.mail.smtp.ssl.enable=true
  • 获取授权码:在QQ邮箱中的设置—账户—开启pop3和smtp服务
  • Spring单元测试
@Autowired
JavaMailSenderImpl javaMailSender;
//邮件设置1:一个简单的邮件
@Test
void contextLoads() {
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setSubject("Hello World");
    mailMessage.setText("Content Text");

    mailMessage.setTo("xxxxxxxx@163.com");
    mailMessage.setFrom("xxxxxxx@qq.com");
    javaMailSender.send(mailMessage);
}

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

    //正文
    helper.setSubject("Hello World!!");
    helper.setText("<p style='color:red'>Content Text</p>", true);

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

    helper.setTo("xxxxxxxx@163.com");
    helper.setFrom("xxxxxxx@qq.com");

    javaMailSender.send(mimeMessage);

}
  • 测试成功
  • 只需要使用Thymeleaf进行前后端结合即可开发自己的网站邮箱收发功能啦

28、定时任务

  • 项目开发中经常需要执行一些定时任务,比如在每天凌晨分析一次前一天的日志信息,Spring提供了异步执行任务调度的方式,两个接口和两个注解

  • TaskExecutor接口(任务执行者),TaskScheduler接口(任务调度者)

  • @Scheduled——什么时候执行,@EnableScheduling——开启定时功能的注解

28.1 Cron表达式

  • 总共6位,分别代表:秒,分,时,日,月,星期几

  • 字段

字段允许值允许特殊字符
0-59, - * /
0-59, - * /
小时0-23, - * /
日期1-31, - * / ? L W C
月份1-12, - * /
星期0-1或SUN-SAT,0和7都是SUN, - * / ? L W C
  • 特殊字符
特殊字符代表含义
,枚举
-区间
*任意
/步长
?日/星期冲突匹配
L最后
W工作日
C和calendar练习后计算过的值
#星期,4#2 第二个星期三
(1)0/2 * * * * ?   表示每2秒 执行任务
(2)0 0/2 * * * ?   表示每2分钟 执行任务
(3)0 0 2 1 * ?   表示在每月的1日的凌晨2点调整任务
(4)0 15 10 ? * MON-FRI   表示周一到周五每天上午10:15执行作业
(5)0 15 10 ? 6L 2002-2006   表示2002-2006年的每个月的最后一个星期五上午10:15执行作
(6)0 0 10,14,16 * * ?   每天上午10点,下午2点,4点
(7)0 0/30 9-17 * * ?   朝九晚五工作时间内每半小时
(8)0 0 12 ? * WED   表示每个星期三中午12点
(9)0 0 12 * * ?   每天中午12点触发
(10)0 15 10 ? * *   每天上午10:15触发
(11)0 15 10 * * ?     每天上午10:15触发
(12)0 15 10 * * ?   每天上午10:15触发
(13)0 15 10 * * ? 2005   2005年的每天上午10:15触发
(14)0 * 14 * * ?     在每天下午2点到下午2:59期间的每1分钟触发
(15)0 0/5 14 * * ?   在每天下午2点到下午2:55期间的每5分钟触发
(16)0 0/5 14,18 * * ?     在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
(17)0 0-5 14 * * ?   在每天下午2点到下午2:05期间的每1分钟触发
(18)0 10,44 14 ? 3 WED   每年三月的星期三的下午2:10和2:44触发
(19)0 15 10 ? * MON-FRI   周一至周五的上午10:15触发
(20)0 15 10 15 * ?   每月15日上午10:15触发
(21)0 15 10 L * ?   每月最后一日的上午10:15触发
(22)0 15 10 ? * 6L   每月的最后一个星期五上午10:15触发
(23)0 15 10 ? * 6L 2002-2005   2002年至2005年的每月的最后一个星期五上午10:15触发
(24)0 15 10 ? * 6#3   每月的第三个星期五上午10:15触发

28.2 测试

  • 新建一个ScheduledService
@Service
public class ScheduledService {
    //在特定时间执行这个方法
    //cron表达式
    //六位分别代表: 秒 分 时 日 月 星期几

    /*
        0 49 11 * * ?   每天的11点49分00秒执行
        0 0/5 11,12 * * ?   每天的11点和12点每隔五分钟执行一次
        0 15 10 ? * 1-6     每个月的周一到周六的10点15分执行一次
        0/2 * * * * ?     每2秒执行一次
     */
    @Scheduled(cron = "0/2 * * * * ?" )
    public void hello(){
        System.out.println("你被执行啦");
    }
}
  • 在主程序上增加@EnableScheduling,开启定时任务功能
//开启定时功能的注解
@EnableScheduling
@EnableAsync
public class Springboot09TestApplication {

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值