springboot+多线程实现邮件发送(定时任务)

一:实现一个简单的异步任务

1.不适用spring自带的异步注解

service层的AsyncService 类

package com.example.demo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
          
   

    //多线程的简单列子
   
    public void heelo(){
          
   
        try{
          
   
            Thread.sleep(3000);
        } catch (InterruptedException e) {
          
   
            e.printStackTrace();
        }
        System.out.println("数据正在处理......");
    }
}

controller层的

package com.example.demo.controller;

import com.example.demo.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AsynController {
          
   
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
          
   
        asyncService.heelo();
        return "我爱你";
    }
}

页面会等待3秒后出现”我爱你“

2.使用spring自带的@Async列子,页面会先出现“我爱你” 在启动类中增加@EnableAsync

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;


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

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

}
@Service
public class AsyncService {
          
   

    //多线程的简单列子
    @Async
    public void heelo(){
          
   
        try{
          
   
            Thread.sleep(3000);
        } catch (InterruptedException e) {
          
   
            e.printStackTrace();
        }
        System.out.println("数据正在处理......");
    }
}

二:spingboot实现邮件发送

1.导入javax.mail

<!--        导入javax.mail -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

2.yaml文件中进行配置

3.在测试类尝试发送邮件

实现一个能发送html和图片的代码

将上面的代码编写成一个类

三:定时任务

1.定时任务需要两个注解 @EnableScheduling // 开启定时功能的注解,放到启动类里面 @Scheduled //什么时候执行 cron表达式 建立一个ScheduledService类

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class ScheduledService {
          
   

    //cron表达式
    /**
     * 秒 分 时 日 月 周几
     * 我的当前时间时15:55分
     * ?代表你不确定现在是星期几
     * 0-7代表每天都执行
     *   0 56 15 * * ? 每天的15点56分0秒执行一次
     *   0 0/5 15 10,18 * ? 每天10点和18点,每隔五分种执行一次
     *   
     *
     * */

    @Scheduled(cron = "0 56 15 * * ?")
    public void hello(){
          
   
        System.out.println("hello,你被执行了");
    }
}
经验分享 程序员 微信小程序 职场和发展