#处理大批量数据的时候,效率很慢。所以考虑一下使用多线程。
刚开始自己手写的一套,用了线程池启动固定的线程数进行跑批。但是后来老大考虑到自己手写的风险不好控制,所以使用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 {
@Bean
public 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 {
@Async
public Future<Long> rtn1() throws Exception {
//do something
//有返回值的时候,可以返回string,long之类的。
return new AsyncResult<>(1);
}
@Async
public 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 {
@Autowired
private 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);
}
}