本文主要是介绍springboot @Async 注解实现方法异步,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#处理大批量数据的时候,效率很慢。所以考虑一下使用多线程。
刚开始自己手写的一套,用了线程池启动固定的线程数进行跑批。但是后来老大考虑到自己手写的风险不好控制,所以使用spring的方法。
这里没有详细介绍,只有简单的demo,只会用,不懂原理:
一、springboot的App类需要的注解
package com.xxx.xxx.xxx;import java.util.concurrent.ThreadPoolExecutor;import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;/*** 类功能说明:服务生产者启动类* <p>* <strong></strong>* </p>** @version* @author* @since 1.8*/
@Configuration
@EnableAsync
public class Application extends SpringBootServletInitializer {@Beanpublic TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();// 设置核心线程数executor.setCorePoolSize(5);// 设置最大线程数executor.setMaxPoolSize(60);// 设置队列容量executor.setQueueCapacity(20);// 设置线程活跃时间(秒)executor.setKeepAliveSeconds(60);// 设置默认线程名称executor.setThreadNamePrefix("what-");// 设置拒绝策略executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 等待所有任务结束后再关闭线程池executor.setWaitForTasksToCompleteOnShutdown(true);return executor;}}
springboot的App类,很简单,就能使用很多东西。
二、service层的注解
package com.xxx.xxx.service.impl;import java.util.concurrent.Future;import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;import com.xxx.xxx.service.XXXAsyncService ;@Service
public class XXXAsyncServiceImpl implements XXXAsyncService {@Asyncpublic Future<Long> rtn1() throws Exception {//do something//有返回值的时候,可以返回string,long之类的。return new AsyncResult<>(1);}@Asyncpublic void rtn2() throws Exception {//do something//这个可以没有返回值.}
}
三、调用层
package com.xxx.xxx.controller;import java.util.concurrent.Future;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import com.xxx.xxx.service.XXXAsyncService;@RestController
@RequestMapping(value="/xxx")
public class XXXAsyncController {@Autowiredprivate XXXAsyncService xxxAsyncService;/*** 这里调用异步方法*/@RequestMapping(value = "/xxx")public void dodo() throws Exception {int threads = 10;//十个线程List<Future<Long>> list = new ArrayList<>();for(int i = 0;i < threads; i++){//这里循环调用异步方法。//如果存在大量数据,可以在这里把数据切片,然后循环调用,分批处理数据。效率杠杠的。list .add(xxxAsyncService.rtn1());}long count = 0;for(Future<Long> l : tsfCountList) {//异步调用需要返回值的时候,这里可以把返回值都放入到list集合中,然后可以统一处理。 这里的get()是阻塞的,因为需要所以异步方法返回,在继续执行。count += l.get();}System.out.println("调用次数:" + count);}
}
以上全是手写,删删减减,抄来抄去,没有验证的代码。希望对别人有一点点帮助。记录下来,以后用的时候,省的忘了,查起来麻烦。。
这篇关于springboot @Async 注解实现方法异步的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!