springboot之异步任务、定时任务、以及发送邮件

  • springboot开启一个异步任务

如果在开发中遇到需要发送邮件的任务之类的话,为了不影响用户的体验,我们就可以在后台开启一个线程去执行,然后把结果先返回给用户。

如何开启一个线程。springboot已经给我们封装好了,只需要加上一个注解就可以了。
在控制层中注入,然后调用服务层的方法即可。

控制层代码:

@Autowired
AsyncService asyncService;

@RequestMapping("/hello")
public String hello(){
   asyncService.hello();
   return "OK";
}

然后在服务层的方法上面加上以下注解就可以了。

@Async

最后,就是在springboot的启动类开启多线程。加上注解

@EnableAsync
  • springboot开启一个定时任务

springboot已经有了封装好的方法,直接用就可以了

在需要定时的方法中加入注解Scheduled,传入cron就可以了。不知道cron是什么的百度一下就明白了

@Scheduled(cron = "0 22 22 * * ?")

然后一样在启动类加上注解

@EnableScheduling

就可以了!

  • springboot发送邮件

使用springboot发送邮件需要导入start的包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

JavaMailSender是springboot已经封装好的,我们只需要做简单的操作就可以了,记得自动注入

	@Autowired
    JavaMailSender mailSender;

    void contextLoads() {
        //一个简单的邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("关于邮件发送");//设置主题
        mailMessage.setText("这是测试邮件发送");//设置内容
        mailMessage.setTo("xxxx@qq.com");//发送给谁
        mailMessage.setFrom("xxxx@qq.com");//从哪里发送出去
        mailSender.send(mailMessage);
    }

    void contextLoads2() throws MessagingException {
        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("关于复杂邮件发送++");
        helper.setText("<p style='color:red'>这是测试复杂邮件发送</p>",true);
        //添加附件
        helper.addAttachment("1.jpg", new File("C:\\Users\\nanth\\Pictures\\Saved Pictures\\01.jpg"));

        helper.setTo("xxxx@qq.com");
        helper.setFrom("xxxx@qq.com");
        mailSender.send(mimeMessage);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值