1.异步任务

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

主要使用两个注解完成,@EnableAysnc、@Aysnc

(1).Springboot04TaskApplication.java

@EnableAsync    //开启异步注解功能

@SpringBootApplication

public class Springboot04TaskApplication {

public static void main(String[] args) {

SpringApplication.run(Springboot04TaskApplication.class, args);

}

}

(2).AsyncController.java

package com.hosystem.task.controller;

import com.hosystem.task.service.AsyncService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class AsyncController {

@Autowired

AsyncService asyncService;

@GetMapping("/hello")

public String hello(){

asyncService.hello();

return "success";

}

}

(3).AsyncService.java

package com.hosystem.task.service;

import org.springframework.scheduling.annotation.Async;

import org.springframework.stereotype.Service;

@Service

public class AsyncService {

//通知spring这是一个异步方法

    @Async

public void hello(){

try {

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("处理数据....");

}

}

2.定时任务

开发中经常需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息。Spring为我们提供了异步执行任务调度的方式,提供TaskExecutor 、TaskScheduler 接口。

使用到的注解有两个,@EnableScheduling、@Scheduled

Cron表达式:

(1).ScheduledService.java

package com.hosystem.task.service;

import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.stereotype.Service;

@Service

public class ScheduledService {

/**

     *  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/4 * * * * 0-7")  //4秒执行一次

    public void hello() {

System.out.println("hello ...");

}

}

(2).Springboot04TaskApplication.java

package com.hosystem.task;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.scheduling.annotation.EnableAsync;

import org.springframework.scheduling.annotation.EnableScheduling;

import org.springframework.scheduling.annotation.Scheduled;

@EnableScheduling //开启基于注解定时任务

@SpringBootApplication

public class Springboot04TaskApplication {

public static void main(String[] args) {

SpringApplication.run(Springboot04TaskApplication.class, args);

}

}

3.邮件任务

(1).导入pom.xml

<!--mail-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-mail</artifactId>

</dependency>

(2).开启POP3/SMTP

(3).开启IMAP/SMTP

(4).生成授权码

(5).applicaiton.properties

server.port=80

#配置邮箱信息

spring.mail.username=username@qq.com

#授权码

spring.mail.password=password

#smtp地址

spring.mail.host=smtp.qq.com

spring.mail.protocol=smtp

spring.mail.properties.mail.smtp.ssl.enable=true

(6).Springboot04TaskApplicationTests.java

SendMailTest测试邮箱发送,一定要在mail中开启SMTP

package com.hosystem.task;

import org.junit.jupiter.api.Test;

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 javax.mail.internet.MimeMessage;

import java.io.File;

@SpringBootTest

class Springboot04TaskApplicationTests {

@Autowired

JavaMailSenderImpl mailSender;

@Test

public void contextLoads() {

SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

//邮件设置

      simpleMailMessage.setSubject("通知-----");

simpleMailMessage.setText("学习java");

  //setTo:目的邮件地址  setFrom:发送邮件地址

simpleMailMessage.setTo("username@163.com");

simpleMailMessage.setFrom("username@qq.com");

mailSender.send(simpleMailMessage);

}

@Test

public void test01() throws Exception{

//1.创建一个复杂的消息邮件

      MimeMessage mimeMessage = mailSender.createMimeMessage();

MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

//邮件设置

      helper.setSubject("通知-----");

/**

       *     public void setText(String text) throws MessagingException {this.setText(text, false);

       }

       */

      helper.setText("<b style='color:red'>学习java</b>",true);

  //setTo:目的邮件地址  setFrom:发送邮件地址

helper.setTo("username@163.com");

helper.setFrom("username@qq.com");

//上传文件

      helper.addAttachment("8a92681cb892bf78ec83af62f2b6a82.jpg",new File("E:\\Users\\Asuna\\Desktop\\html\\8a92681cb892bf78ec83af62f2b6a82.jpg"));

helper.addAttachment("8f82df421233241732db6ec6baed07e.jpg",new File("E:\\Users\\Asuna\\Desktop\\html\\8f82df421233241732db6ec6baed07e.jpg"));

mailSender.send(mimeMessage);

}

}

参考文档:

https://github.com/spring-projects/spring-boot/tree/v2.1.0.RELEASE/spring-boot-project/spring-boot-starters

8、Spring Boot任务的更多相关文章

  1. 玩转spring boot——快速开始

    开发环境: IED环境:Eclipse JDK版本:1.8 maven版本:3.3.9 一.创建一个spring boot的mcv web应用程序 打开Eclipse,新建Maven项目 选择quic ...

  2. 【微框架】之一:从零开始,轻松搞定SpringCloud微框架系列--开山篇(spring boot 小demo)

    Spring顶级框架有众多,那么接下的篇幅,我将重点讲解SpringCloud微框架的实现 Spring 顶级项目,包含众多,我们重点学习一下,SpringCloud项目以及SpringBoot项目 ...

  3. 玩转spring boot——开篇

    很久没写博客了,而这一转眼就是7年.这段时间并不是我没学习东西,而是园友们的技术提高的非常快,这反而让我不知道该写些什么.我做程序已经有十几年之久了,可以说是彻彻底底的“程序老炮”,至于技术怎么样?我 ...

  4. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  5. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  6. 玩转spring boot——结合JPA入门

    参考官方例子:https://spring.io/guides/gs/accessing-data-jpa/ 接着上篇内容 一.小试牛刀 创建maven项目后,修改pom.xml文件 <proj ...

  7. 玩转spring boot——结合JPA事务

    接着上篇 一.准备工作 修改pom.xml文件 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  8. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  9. 玩转spring boot——结合jQuery和AngularJs

    在上篇的基础上 准备工作: 修改pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=&q ...

  10. 玩转spring boot——MVC应用

    如何快速搭建一个MCV程序? 参照spring官方例子:https://spring.io/guides/gs/serving-web-content/ 一.spring mvc结合thymeleaf ...

随机推荐

  1. 关于node回调函数中同步和异步操作的理解

    1.node的回调函数:如果一个方法的参数是另一个函数的名字,则这个参数本身就要回调函数,这个函数就是回调函数 1).同步操作文件(阻塞I/O)      同步就是一个人干完这个再干那个--    所 ...

  2. 全球首个优秀的华人.net微服务框架 作者:百大僧

    话不多说,直接上地址 https://gitee.com/shoubashou/NetCoreMicroService,目标斩获10000star, 通往牛逼的路上,风景差得让人只说脏话. 是全球首个 ...

  3. centos7安装ifconfig

    1,找出哪个包提供了ifconfig命令 yum provides ifconfig 2,通过输出,发现是net-tools提供了ifconfig命令 yum install net-tools

  4. 关于c++ string类的一些使用

    主要最近要用的上 才整理一下 用string类别忘了导入头文件 #include <string> 注意这个细节:cout 可直接输出 string 类的对象的内容 但是printf不可以 ...

  5. D. Equalize the Remainders 解析(思維)

    Codeforce 999 D. Equalize the Remainders 解析(思維) 今天我們來看看CF999D 題目連結 題目 略,請直接看原題 前言 感覺要搞個類似\(stack\)的東 ...

  6. 关于eslint的使用与配置,以及prettier的使用

    eslint官网:https://eslint.bootcss.com/docs/user-guide/getting-started eslint配置:http://eslint.cn/docs/r ...

  7. CodeForces 1418D Trash Problem

    题意 数轴上有 \(n\) 个点,每一次你可以将所有位置在 \(x\) 的点移动到 \(x-1\) 或者是移动到 \(x+1\),花费为 \(1\). 有 \(q\) 次操作,每一次会在数轴上添加一个 ...

  8. 专题一:why redis ?

    一.NoSQL   现在互联网应用其中有两个特点:(1)海量用户(2)不可避免地高并发.常常因为这样,我们网站或者服务器将面临崩溃的风险.而多用户.高并发只是现象,究其根源,罪魁祸首就是关系型数据库, ...

  9. 如何k个一组反转链表

    之前的文章「递归反转链表的一部分」讲了如何递归地反转一部分链表,有读者就问如何迭代地反转链表,这篇文章解决的问题也需要反转链表的函数,我们不妨就用迭代方式来解决. 本文要解决「K 个一组反转链表」,不 ...

  10. GANSS 87C键盘在Linux无法正常使用的解决办法

    前几天在狗东入手可以一把GANSS的87C键盘,满心欢喜拆开来用却发现在开发电脑(Deepin和ubuntu)上F1-F12都不能正常使用,这对一个搞web开发的人来说,无疑是要了我的老命,无奈找各种 ...