当前位置: 移动技术网 > IT编程>开发语言>Java > SpringBoot实现定时任务和异步调用

SpringBoot实现定时任务和异步调用

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了springboot实现定时任务和异步调用的具体代码,供大家参考,具体内容如下

环境:

jdk1.8;spring boot2.0.2;maven3.3

摘要说明:

定时任务:定时任务是业务场景中经常出现的一种情况如:定时发送邮件,短信、定时统计监控数据、定时对账等

异步调用:一个都买流程可能包括下单、发货通知、短信推送、消息推送等,其实除了下单这个主要程序是主程序,其他子程序可以同时进行且不影响主程序的运行,这个时候就可以使用异步调用来调用这些子程序;

步骤:

1.定时任务

a.在spring boot主类上使用注解@enablescheduling启动定时任务:

package com.example.demo;
 
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.scheduling.annotation.enablescheduling;
 
//启动定时任务
@enablescheduling
@springbootapplication
public class demoapplication {
 
 public static void main(string[] args) {
 springapplication.run(demoapplication.class, args);
 }
}

b.实现定时任务(使用@component注解来标注组件)

 /**
 * @模块名:demo
 * @包名:com.example.demo.test1.component
 * @描述:schedulingcomponent.java
 * @版本:1.0
 * @创建人:cc
 * @创建时间:2018年9月29日上午10:19:37
 */
 
package com.example.demo.test1.component;
 
import java.util.date;
 
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
 
/**
 * @模块名:demo
 * @包名:com.example.demo.test1.component @类名称: schedulingcomponent
 * @类描述:【类描述】用于测试定时任务 @版本:1.0
 * @创建人:cc
 * @创建时间:2018年9月29日上午10:19:37
 */
@component
public class schedulingcomponent {
 
 /**
 * 
 * @方法名:testscheduling1
 * @方法描述【方法功能描述】测试定时任务,没三秒执行一次
 * @修改描述【修改描述】
 * @版本:1.0
 * @创建人:cc
 * @创建时间:2018年9月29日 上午10:26:20
 * @修改人:cc
 * @修改时间:2018年9月29日 上午10:26:20
 */
 @scheduled(fixedrate = 3000)
 public void testscheduling1() {
 
 system.out.println("执行时间为"+new date()+"执行testscheduling1");
 }
}
@scheduled注解和之前spring使用xml配置定时任务类似:

@scheduled(fixedrate = 5000) :上一次开始执行时间点之后5秒再执行
@scheduled(fixeddelay = 5000) :上一次执行完毕时间点之后5秒再执行
@scheduled(initialdelay=1000, fixedrate=5000) :第一次延迟1秒后执行,之后按fixedrate的规则每5秒执行一次
@scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则

c.上述方法写好后启动服务看下控制台结果:

2.异步调用

a.首先在spring boot主类上使用注解@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 demoapplication {
 
 public static void main(string[] args) {
 springapplication.run(demoapplication.class, args);
 }
}

b.sping boot异步调用很简单,只需使用@async注解标明方法(接口方法)异步

package com.example.demo.test1.component;
 
public interface taskcomponent {
 void test1() throws exception;
 
 void test2() throws exception;
 
 void test3() throws exception;
}
package com.example.demo.test1.component.impl;
 
import java.util.random;
 
import org.springframework.scheduling.annotation.async;
import org.springframework.stereotype.component;
 
import com.example.demo.test1.component.taskcomponent;
 
@component
public class taskcomponentimpl implements taskcomponent {
 public static random random = new random();
 
 @override
 @async
 public void test1() throws interruptedexception {
 system.out.println("开始做任务一");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
 
 }
 
 @override
 @async
 public void test2() throws interruptedexception {
 system.out.println("开始做任务二");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
 
 }
 
 @override
 @async
 public void test3() throws interruptedexception {
 system.out.println("开始做任务三");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
 
 }
 
}

c.使用测试类进行测试:

package com.example.demo;
 
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.boot.test.context.springboottest.webenvironment;
import org.springframework.boot.web.server.localserverport;
import org.springframework.test.context.junit4.springrunner;
 
import com.example.demo.test1.component.taskcomponent;
 
@runwith(springrunner.class)
// 引入springboottest并生成随机接口
@springboottest(webenvironment = webenvironment.random_port)
public class asynctest {
 
 // 注入随机接口
 @localserverport
 private int port;
 
 @autowired
 private taskcomponent taskcomponent;
 
 @test
 public void testtask() {
 try {
 taskcomponent.test1();
 taskcomponent.test2();
 taskcomponent.test3();
 system.out.println("执行主线程");
 // 主线程休眠10秒等待上述异步方法执行
 thread.sleep(10000);
 }
 catch (exception e) {
 system.out.println(e);
 }
 
 }
}

执行结果如下;可以看出三个异步方法互不影响,且不影响主线程的运行

执行主线程
开始做任务一
开始做任务二
开始做任务三
完成任务一,耗时:1401毫秒
完成任务二,耗时:4284毫秒
完成任务三,耗时:5068毫秒

d.对于这些异步执行的调用往往会给我们带来思考是不是异步调用越多越好,答案当然是否;所以在这里引入线程池来进行异步调用控制:

在spring boot主类上标注线程池:

package com.example.demo;
 
import java.util.concurrent.executor;
import java.util.concurrent.threadpoolexecutor;
 
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.enableasync;
import org.springframework.scheduling.annotation.enablescheduling;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
 
//启动定时任务
 
@enablescheduling
@springbootapplication
public class demoapplication {
 
 public static void main(string[] args) {
 springapplication.run(demoapplication.class, args);
 }
 
 // 启动异步调用
 @enableasync
 @configuration
 class taskpoolconfig {
 // 核心线程数(setcorepoolsize)10:线程池创建时候初始化的线程数
 // 最大线程数(setmaxpoolsize)20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
 // 缓冲队列(setqueuecapacity)200:用来缓冲执行任务的队列
 // 允许线程的空闲时间(setkeepaliveseconds)60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
 // 线程池名的前缀(setthreadnameprefix):设置好了之后可以方便我们定位处理任务所在的线程池
 // 线程池对拒绝任务的处理策略(setrejectedexecutionhandler):这里采用了callerrunspolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute
 // 方法的调用线程中运行被拒绝的任务(setwaitfortaskstocompleteonshutdown);如果执行程序已关闭,则会丢弃该任务
 // setwaitfortaskstocompleteonshutdown(true)该方法就是这里的关键,用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的bean,这样这些异步任务的销毁就会先于redis线程池的销毁。
 // 同时,这里还设置了setawaitterminationseconds(60),该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住。
 @bean("taskexecutor")
 public executor taskexecutor() {
 threadpooltaskexecutor executor = new threadpooltaskexecutor();
 executor.setcorepoolsize(10);
 executor.setmaxpoolsize(20);
 executor.setqueuecapacity(200);
 executor.setkeepaliveseconds(60);
 executor.setthreadnameprefix("taskexecutor-");
 executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
 executor.setwaitfortaskstocompleteonshutdown(true);
 executor.setawaitterminationseconds(60);
 return executor;
 }
 }
}

在方法实现类上使用@async的同时标注线程池:

package com.example.demo.test1.component.impl;
 
import java.util.random;
 
import org.springframework.scheduling.annotation.async;
import org.springframework.stereotype.component;
 
import com.example.demo.test1.component.taskcomponent;
 
@component
public class taskcomponentimpl implements taskcomponent {
 public static random random = new random();
 
 @override
 @async("taskexecutor")
 public void test1() throws interruptedexception {
 system.out.println("开始做任务一");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
 
 }
 
 @override
 @async("taskexecutor")
 public void test2() throws interruptedexception {
 system.out.println("开始做任务二");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
 
 }
 
 @override
 @async("taskexecutor")
 public void test3() throws interruptedexception {
 system.out.println("开始做任务三");
 long start = system.currenttimemillis();
 thread.sleep(random.nextint(10000));
 long end = system.currenttimemillis();
 system.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
 
 }
 
}

再次调用测试来发现结果没什么区别:

执行主线程
开始做任务一
开始做任务二
开始做任务三
完成任务一,耗时:1117毫秒
完成任务二,耗时:3964毫秒
完成任务三,耗时:8886毫秒

接着我们修改线程池线程数为2:

executor.setcorepoolsize(2);
executor.setmaxpoolsize(2);

再次启动测试类可以看到,同时执行的线程数为2,只有等待前一个线程结束才能执行一个新的线程;

执行主线程
开始做任务一
开始做任务二
完成任务二,耗时:620毫秒
开始做任务三
完成任务一,耗时:2930毫秒
完成任务三,耗时:4506毫秒

3.demo地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网