1.配置
# 应用名称 spring.application.name=task-springboot # 应用服务 WEB 访问端口 server.port=8080 spring.mail.username=565482647@qq.com spring.mail.password=kcdolulfhhfvbfjb #发送的服务器 spring.mail.host=smtp.qq.com #开启加密 spring.mail.properties.mail.smtp.ssl.enable=true
2.在主函数中增加注释
@EnableAsync//开启异步注解功能 @EnableScheduling//开启定时功能的注解 @SpringBootApplication public class TaskSpringbootApplication { public static void main(String[] args) { SpringApplication.run(TaskSpringbootApplication.class, args); } }
3.测试邮件发送
@SpringBootTest class TaskSpringbootApplicationTests { @Autowired JavaMailSenderImpl mailSender; @Test void contextLoads() { //一个简单的邮件 SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setSubject("你好老沙"); simpleMailMessage.setText("我本来可以写个循环每隔一秒发送一封,可是我没有,所以我是个好人"); simpleMailMessage.setTo("1418084771@qq.com"); simpleMailMessage.setFrom("565482647@qq.com"); mailSender.send(simpleMailMessage); } @Test void contextLoads2() throws MessagingException { //一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); //组装 MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);//true开启多文件 mimeMessageHelper.setSubject("写给自己的邮件"); mimeMessage.setText("谢谢你 带我来"); //mimeMessageHelper.addAttachment("1.png",new File("C:\\Users\\56548\\Desktop\\1.png")); mimeMessageHelper.setTo("2945826643@qq.com"); mimeMessageHelper.setFrom("565482647@qq.com"); mailSender.send(mimeMessage); } }
4.用于异步的代码
@Service public class AsyncService { //告诉spring这是一个异步的办法 测试一个异步方法 @Async public void hello(){ try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "数据正在处理...." ); } }
5.用于定时的代码
@Service public class ScheduledService { //秒 分 时 日 月 周几 //每天的13.24执行代码 //cron表达式-逆天 @Scheduled(cron="0 24 13 * * ?") public void hello(){ System.out.println("你被执行了"); } }
6.Controller-->测试异步
@RestController public class AsyncController { @Autowired AsyncService asyncService; @RequestMapping("/hello") public String hello(){ asyncService.hello(); return "ok"; } }