任务管理(异步任务定时任务发送邮件)

Posted 流星蝴蝶没有剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了任务管理(异步任务定时任务发送邮件)相关的知识,希望对你有一定的参考价值。

任务管理(异步任务、定时任务、发送邮件)

1. 异步

1.1 无返回值

  1. @EnableAsync 开启注解异步任务支持

  2. 异步调用

package wx0725.top.service;

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

@Service
public class MyAsyncService 
    @Async
    public void sendSMS() throws Exception 
        System.out.println("调用短信验证码业务.");
        Long start = System.currentTimeMillis();
        Thread.sleep(5000);
        Long end = System.currentTimeMillis();
        System.out.println("短信业务耗时: " + (end - start));
    

  1. 控制器访问,发送消息
package wx0725.top.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import wx0725.top.service.MyAsyncService;

@Controller
public class MyAsyncController 
    @Autowired
    private MyAsyncService myAsyncService;

    @ResponseBody
    @GetMapping("/sendSMS")
    public String sendSMS() throws Exception 
        Long start = System.currentTimeMillis();
        myAsyncService.sendSMS();
        Long end = System.currentTimeMillis();
        return "短信发送成功。" + "访问耗时:" + (end - start);
    



1.2 有返回值

带返回值的业务


    @Async
    public Future<String> getA() throws Exception 
        Long start = System.currentTimeMillis();
        Thread.sleep(5000);
        String str = "** A 业务处理";
        Long end = System.currentTimeMillis();
        return new AsyncResult<String>(str + (end - start));
    

    @Async
    public Future<String> getB() throws Exception 
        Long start = System.currentTimeMillis();
        Thread.sleep(5000);
        String str = "** B 业务处理";
        Long end = System.currentTimeMillis();
        return new AsyncResult<String>(str + (end - start));
    

添加控制器:

    @ResponseBody
    @GetMapping("/staticstics")
    public String staticStics() throws Exception 
        Long start = System.currentTimeMillis();
        String str = myAsyncService.getA().get() + myAsyncService.getB().get();
        Long end = System.currentTimeMillis();
        return str + "访问耗时:" + (end - start);
    

2. 定时任务

@EnableScheduling

package wx0725.top.service;

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

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class ScheduledTaskService 
    private static final SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private Integer integer1 = 1;
    private Integer integer2 = 1;
    private Integer integer3 = 1;
    private Integer integer4 = 1;

    //    每6秒访问执行一次,并且项目启动立即执行
    @Scheduled(fixedRate = 6000)
    public void scheduleTask1() 
        System.out.println("A: 第" + (integer1++) + "次执行,当前时间为:" + s.format(new Date()));
    

    //    每6秒访问执行一次,并且项目启动后立即执行
    @Scheduled(fixedDelay = 6000)
    public void scheduleTask2() 
        System.out.println("B: 第" + (integer2++) + "次执行,当前时间为:" + s.format(new Date()));
    

    //  每6秒访问执行一次,并且项目启动后延时2秒执行
    @Scheduled(initialDelay = 2000, fixedDelay = 6000)
    public void scheduleTask3() 
        System.out.println("C: 第" + (integer3++) + "次执行,当前时间为:" + s.format(new Date()));
    

    //    每分钟整秒执行
    @Scheduled(cron = "0 * * * * *")
    public void scheduleTask4() 
        System.out.println("D: 第" + (integer4++) + "次执行,当前时间为:" + s.format(new Date()));
    




3. 发送邮件

3.1 发送纯文本

定制发送服务

package wx0725.top.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

@Service
public class SendEmailService 
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("$spring.mail.username")
    private String form;

    public String sendSimpleEmail(String to, String subject, String text) 
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(form);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setText(text);
        try 
            javaMailSender.send(simpleMailMessage);
            return "邮箱发送成功";
         catch (Exception e) 
            e.printStackTrace();
            return "邮箱发送失败";
        
    


控制器发送

package wx0725.top.controller;

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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import wx0725.top.service.SendEmailService;

@Controller
public class SendEmail 

    @Autowired
    private SendEmailService service;

    @RequestMapping(value = "/sendEmailText", method = RequestMethod.GET)
    @ResponseBody
    public String sendEmailText(@RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("subject") String text) 
        return service.sendSimpleEmail(to, subject, text);
    



测试

3.2 发送图片和附件

定制发送服务:


    public String sendMimeMessage(String to, String subject, String text, String filePath, String rscId, String rscPath) throws Exception 
        MimeMessage message = javaMailSender.createMimeMessage();
        try 
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setFrom(form);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(text, true);
//             设置静态资源(图片)
            FileSystemResource img = new FileSystemResource(new File(rscPath));
            mimeMessageHelper.addInline(rscId, img);
//            设置附件
            FileSystemResource file = new FileSystemResource(new File(rscPath));
            String filename = filePath.substring(filePath.lastIndexOf("\\\\")+1);
            System.out.println(filename);
            mimeMessageHelper.addAttachment(filename, file);
            javaMailSender.send(message);
            return "邮件发送成功";
         catch (Exception e) 
            e.printStackTrace();
            return "邮件发送失败";
        
    

控制器:

    @RequestMapping(value = "/sendEmailFileAndImg", method = RequestMethod.GET)
    @ResponseBody
    public String sendEmailFileAndImg(@RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("subject") String text) throws Exception 
        StringBuilder stringBuilder = new StringBuilder();
        String rscId = new Date().toString();
        stringBuilder.append(String.format("<html><head></head><body><h1>你好: %s</h1><img src=\\"cid:%s\\" /></body></html>", text, rscId));
        String filePath = "D:\\\\201817020085\\\\bitbug_favicon.ico";
        String rscPath = "D:\\\\201817020085\\\\bitbug_favicon.ico";
        return service.sendMimeMessage(to, subject, text, filePath, rscId, rscPath);
    

测试

3.3 发送模板页面

定制:


    public String sendTemplateEmail(String to, String subject, String text) 
        MimeMessage message = javaMailSender.createMimeMessage();
        try 
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setFrom(form);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(text);
            javaMailSender.send(message);
            return "邮箱发送成功";
         catch (Exception e) 
            e.printStackTrace();
            return "邮箱发送失败";
        
    

控制器:


    @Autowired
    private TemplateEngine templateEngine;

    @RequestMapping(value = "/sendTemplateEmail", method = RequestMethod.GET)
    @ResponseBody
    public String sendTemplateEmail(@RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("subject") String text) throws Exception 
        StringBuilder stringBuilder = new StringBuilder();
        Context context = new Context();
        context.setVariable("username", "文轩");
        context.setVariable("code", "6666");
        String emailTemplate = templateEngine.process("email/email_code", context);
        return service.sendTemplateEmail(to, subject, text);
    

依赖积累

pom.xml

    <dependencies>
        <!-- Spring Boot提供的配置处理器依赖,代码提示 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!--        web 开发场景-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--        热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!--    静态模板依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


        <!--        IO 操作-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <vers

以上是关于任务管理(异步任务定时任务发送邮件)的主要内容,如果未能解决你的问题,请参考以下文章

7.4 异步定时和邮件发送任务

SpringBoot异步定时邮件任务

异步定时邮件任务

4.异步邮件发送和定时任务

CELERY 定时任务

21SpringBoot 异步任务,定时任务,邮件任务