Spring的异步线程处理

Spring封装了JDK的线程池和线程调用,并使用标签就可以开启多线程调用。

先进行一个Spring的线程池配置

@Configuration @EnableAsync public class ThreadPoolConfig implements AsyncConfigurer { @Bean @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()); executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 5); executor.setQueueCapacity(Runtime.getRuntime().availableProcessors() * 2); executor.setThreadNamePrefix("this-executor-"); executor.initialize(); return executor; }

@Bean

@Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return new SimpleAsyncUncaughtExceptionHandler(); } }

再编写一个Service的异步方法调用,这里是带返回值的,不带返回值的方法比较简单,这里就不举例了。

@Service @Slf4j public class ThreadTasks { _/** _ * 如果异步方法有返回值,一定要使用Future包装,否则无法返回 * _@return _ * @throws _InterruptedException _ */ @Async public Future<String> startTask() throws InterruptedException { Thread.sleep(3000); log.info("this is async task"); return new AsyncResult<>("123456"); } }

最后写一个Controller,对该异步方法进行调用

@RestController public class AsyncTaskController { @Autowired private ThreadTasks tasks; @GetMapping("/users-anon/useTask") public String useSyncTask() throws InterruptedException, ExecutionException { Future<String> future = tasks.startTask(); return future.get(); } }

最后运行下来,我们可以看到每次都是不同的线程执行

12020-09-21 16:33:53.027 INFO [user-center,3e635fca3d1259da,d30e8b6372922137,false] 1126 --- [this-executor-1] com.cloud.user.service.ThreadTasks : this is async task 22020-09-21 16:35:27.664 INFO [user-center,9b68efbb2c848d7b,895ed921f6c8fe03,false] 1126 --- [this-executor-2] com.cloud.user.service.ThreadTasks : this is async task
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

SpringBoot异步使用@Async原理及线程池配置

前言在实际项目开发中很多业务场景需要使用异步去完成,比如消息通知,日志记录,等非常常用的都可以通过异步去执行,提高效率,那么在Spring框架中应该如何去使用异步呢使用步骤完成异步操作一般有两种,消息队列MQ,和线程池处理ThreadPoolExecutor而在Spring4中提供的对ThreadPoolExecutor封装的线程池ThreadPoolTa

4、jstack查看线程栈信息

1、介绍利用jps、top、jstack命令找到进程中耗时最大的线程,以及线程状态等等,同时最后还可以显示出死锁的线程查找:FoundoneJavaleveldeadlock即可1、jps获得进程号!(https://oscimg.oschina.net/oscnet/da00a309fa6

KVM调整cpu和内存

一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid