@Async异步调用

就不解释什么是异步调用了,Spring Boot中进行异步调用很简单

1.通过使用@Async注解就能简单的将原来的同步函数变为异步函数

package com.winner.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit; /**
* @author winner_0715
* @date 2018/12/06
*/
@Service
public class TaskServer { @Async
public void doTaskA() throws InterruptedException {
System.out.println("TaskA thread name->" + Thread.currentThread().getName());
Long startTime = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2); Long endTime = System.currentTimeMillis();
System.out.println("TaskA 耗时:" + (endTime - startTime));
} @Async
public void doTaskB() throws InterruptedException {
System.out.println("TaskB thread name->" + Thread.currentThread().getName());
Long startTime = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2);
Long endTime = System.currentTimeMillis();
System.out.println("TaskB耗时:" + (endTime - startTime));
}
}

为了让@Async注解能够生效,还需要在Spring Boot的主程序中配置@EnableAsync,如下所示:

package com.winner;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* @author winner_0715
* @date 2018/12/06
*/
@SpringBootApplication
@EnableAsync
public class SpringBootAsyncApplication { public static void main(String[] args) {
SpringApplication.run(SpringBootAsyncApplication.class, args);
} }

注: @Async所修饰的函数不要定义为static类型,这样异步调用不会生效

测试

package com.winner.web;

import com.winner.service.TaskServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /**
* @author winner_0715
* @description:
* @date 2018/12/6
*/
@RestController
public class HelloController { @Resource
private TaskServer taskServer; @GetMapping("/async")
public String testAsync() throws Exception {
System.out.println("主线程 name -->" + Thread.currentThread().getName());
taskServer.doTaskA();
taskServer.doTaskB();
return "Hello World";
}
}

任务线程和主线程的名称不同,表明是异步执行的!

自定义线程池

前面介绍使用@Async注解来实现异步调用了。对于这些异步执行的控制是我们保障自身应用健康的基本技能。下面介绍通过自定义线程池的方式来控制异步调用的并发。

定义线程池

第一步,定义一个线程池,比如:

package com.winner.threadpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; /**
* @author winner_0715
*/
@Configuration
public class ThreadPoolExecutorConfig {
private static final int THREADS = Runtime.getRuntime().availableProcessors() + 1;
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
// -%d不要少
.setNameFormat("async-task-name-%d")
.setDaemon(true)
.build(); @Bean("taskExecutor")
public Executor taskExecutor() {
return new ThreadPoolExecutor(THREADS, 2 * THREADS,
5, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1024),
threadFactory, (r, executor) -> {
// 打印日志,添加监控等
System.out.println("task is rejected!");
});
}
}

上面我们通过使用ThreadPoolExecutor创建了一个线程池

使用线程池

在定义了线程池之后,我们如何让异步调用的执行任务使用这个线程池中的资源来运行呢?方法非常简单,我们只需要在@Async注解中指定线程池名即可,比如:

package com.winner.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit; /**
* @author winner_0715
* @date 2018/12/06
*/
@Service
public class TaskServer { @Async("taskExecutor")
public void doTaskA() throws InterruptedException {
System.out.println("MsgServer send A thread name->" + Thread.currentThread().getName());
Long startTime = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2); Long endTime = System.currentTimeMillis();
System.out.println("MsgServer send A 耗时:" + (endTime - startTime));
} @Async("taskExecutor")
public void doTaskB() throws InterruptedException {
System.out.println("MsgServer send B thread name->" + Thread.currentThread().getName());
Long startTime = System.currentTimeMillis();
TimeUnit.SECONDS.sleep(2);
Long endTime = System.currentTimeMillis();
System.out.println("MsgServer send B耗时:" + (endTime - startTime));
}
}

测试

package com.winner.web;

import com.winner.service.TaskServer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /**
* @author winner_0715
* @description:
* @date 2018/12/6
*/
@RestController
public class HelloController { @Resource
private TaskServer taskServer; @GetMapping("/async")
public String testAsync() throws Exception {
System.out.println("主线程 name -->" + Thread.currentThread().getName());
taskServer.doTaskA();
taskServer.doTaskB();
return "Hello World";
}
}

测试结果:

主线程 name -->http-nio-8080-exec-1
MsgServer send A thread name->async-task-name-0
MsgServer send B thread name->async-task-name-1
MsgServer send A 耗时:2001
MsgServer send B耗时:2001

SpringBoot自定义线程池处理异步任务的更多相关文章

  1. spring boot / cloud (四) 自定义线程池以及异步处理@Async

    spring boot / cloud (四) 自定义线程池以及异步处理@Async 前言 什么是线程池? 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线 ...

  2. spring boot自定义线程池以及异步处理

    spring boot自定义线程池以及异步处理@Async:什么是线程池?线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线程池线程都是后台线程.每个线程都使 ...

  3. SpringBoot 自定义线程池

    本教程目录: 自定义线程池 配置spring默认的线程池 1. 自定义线程池 1.1 修改application.properties task.pool.corePoolSize=20 task.p ...

  4. SpringBoot 自定义线程池,多线程

    原文:https://www.jianshu.com/p/832f2b162450 我们都知道spring只是为我们简单的处理线程池,每次用到线程总会new 一个新的线程,效率不高,所以我们需要自定义 ...

  5. SpringBoot—自定义线程池及并发定时任务模板

    介绍   在项目开发中,经常遇到定时任务,今天通过自定义多线程池总结一下SpringBoot默认实现的定时任务机制. 定时任务模板 pom依赖 <dependencies> <dep ...

  6. Spring Boot使用@Async实现异步调用:自定义线程池

    前面的章节中,我们介绍了使用@Async注解来实现异步调用,但是,对于这些异步执行的控制是我们保障自身应用健康的基本技能.本文我们就来学习一下,如果通过自定义线程池的方式来控制异步调用的并发. 定义线 ...

  7. 转载-SpringBoot结合线程池解决多线程问题实录;以及自己的总结

    原文地址:https://blog.csdn.net/GFJ0814/article/details/92422245 看看这篇文章(继续学习):https://www.jianshu.com/p/3 ...

  8. Android线程管理之ThreadPoolExecutor自定义线程池

    前言: 上篇主要介绍了使用线程池的好处以及ExecutorService接口,然后学习了通过Executors工厂类生成满足不同需求的简单线程池,但是有时候我们需要相对复杂的线程池的时候就需要我们自己 ...

  9. Android AsyncTask 深度理解、简单封装、任务队列分析、自定义线程池

    前言:由于最近在做SDK的功能,需要设计线程池.看了很多资料不知道从何开始着手,突然发现了AsyncTask有对线程池的封装,so,就拿它开刀,本文将从AsyncTask的基本用法,到简单的封装,再到 ...

随机推荐

  1. Pycharm4.5注册码 激活

    name : newasp ===== LICENSE BEGIN ===== 09086-12042010 00001EBwqd8wkmP2FM34Z05iXch1Ak KI0bAod8jkIffy ...

  2. python+selenium四:iframe查看、定位、切换

    iframe是HTML里面嵌套HTML的一种框架 1.查看iframe 1.Top Window:可直接定位 2.iframe#i:说明此元素在iframe上 3.iframe显示为空:(id或nam ...

  3. linux 图形化与命令模式切换

    vim编辑/etc/inittab 文件如图: 找到红框里的一行.修改数字    3.表示命令模式     5表示图形模式!

  4. 利用反射创建User类的对象

    package com.bjpowernode; public class User { private int age; public String name; public void m1() { ...

  5. Math对象的常用属性和方法

    属性 描述 Math.PI 返回π(3.1415926) 方法 描述 Math.round() 将数字四舍五入到离它最近的整数 Math.sart(n) 返回平方根,例如Math.sart(9)返回3 ...

  6. GDIPlus非典型误用一例

    // ** 初始化GDI+ Gdiplus::GdiplusStartupInput gdiplusStartupInput; // ** 该成员变量用来保存GDI+被初始化后在应用程序中的GDI+标 ...

  7. poj 1751 输出MST中新加入的边

    给出结点的坐标 以及已建好的边 要输出MST中加入的边(已建好的边就不用输出了)结点的编号从1开始注意这题只有一组数据 不能用多组输入 否则就超时(在这被坑惨了Orz) Sample Input 91 ...

  8. c++中关于用stringstream进行的类型转化

    1.将int转化成string类型 #include <iostream> #include <sstream> using namespace std; int main() ...

  9. Android:contentDescription 不是无用

    在写Android的XML布局文件时,在ImageView或ImageButton中经常会碰到一个提示: Missing contentDescription attribute on image. ...

  10. BZOJ.2434.[NOI2011]阿狸的打字机(AC自动机 树状数组 DFS序)

    题目链接 首先不需要存储每个字符串,可以将所有输入的字符依次存进Trie树,对于每个'P',记录该串结束的位置在哪,以及当前节点对应的是第几个串(当前串即根节点到当前节点):对于'B',只需向上跳一个 ...