springboot中的任務(異步任務--定時任務--郵件任務)

1.pom文件java

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zy</groupId>
    <artifactId>spring-boot-task-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-task-demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2.啓動類web

package com.zy;

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

@SpringBootApplication
// 支持異步線程,須要異步調用的service層方法上面加上@Async註解,兩者聯合,可起做用
@EnableAsync
//開啓基於註解的定時任務
@EnableScheduling
public class SpringBootTaskDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBootTaskDemoApplication.class, args); } }

3.controller測試類spring

package com.zy.controller;

import com.zy.service.AsyncServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/task/")
@RestController
public class AsyncController {

    @Autowired
    private AsyncServiceImpl asyncService;

    @RequestMapping("/async")
    public Object async(String name){
        return name;
    }
}

4.service層apache

4.1異步任務實現類安全

 

package com.zy.service;

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

@Service("asyncService")
public class AsyncServiceImpl {

    @Async
    public String async(String name){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "good morning:" + name;
    }

}

4.2定時任務實現類app

package com.zy.service;

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

@Service
public class ScheduledServiceImpl {


    /**
     * second(秒), minute(分), hour(時), day of month(日), month(月), day of week(周幾).
     * 0 * * * * MON-FRI
     *  【0 0/5 14,18 * * ?】 天天14點整,和18點整,每隔5分鐘執行一次
     *  【0 15 10 ? * 1-6】 每一個月的週一至週六10:15分執行一次
     *  【0 0 2 ? * 6L】每一個月的最後一個週六凌晨2點執行一次
     *  【0 0 2 LW * ?】每一個月的最後一個工做日凌晨2點執行一次
     *  【0 0 2-4 ? * 1#1】每一個月的第一個週一凌晨2點到4點期間,每一個整點都執行一次;
     */
    // @Scheduled(cron = "0 * * * * MON-SAT")
    //@Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    // @Scheduled(cron = "0-4 * * * * MON-SAT")


    @Scheduled(cron = "0/50 * * * * MON-SAT")  //每50秒執行一次
    public void saySchedule(){
        System.out.println("saySchedule");
    }
}

 5.郵件任務配置異步

5.1在上述pom中引入javamail的依賴async

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

5.2application.yaml配置maven

spring:
  mail:
    username: aaa@qq.com
#    受權碼,而非真實密碼
    password: bbb
    host: smtp.qq.com
#    配置安全鏈接
    properties: mail.smtp.ssl.enable=true

5.3測試類spring-boot

package com.zy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTaskDemoApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    // 簡單郵件發送
    @Test
    public void contextLoads() {

        SimpleMailMessage message = new SimpleMailMessage();
        //郵件設置
        message.setSubject("通知-今晚開會");
        message.setText("今晚開會");

        message.setTo("ccc@163.com");
        message.setFrom("aaa@qq.com");

        mailSender.send(message);
    }

    @Test
    public void test02() throws  Exception{
        //一、建立一個複雜的消息郵件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        //郵件設置
        helper.setSubject("通知-今晚開會");
        helper.setText("<b style='color:red'>今天 7:30 開會</b>",true);

        helper.setTo("ccc@163.com");
        helper.setFrom("aaa@qq.com");

        //上傳文件
        helper.addAttachment("1.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\1.jpg"));
        helper.addAttachment("2.jpg",new File("C:\\Users\\lfy\\Pictures\\Saved Pictures\\2.jpg"));

        mailSender.send(mimeMessage);

    }

}
相關文章
相關標籤/搜索