SpringBoot另起线程回调

场景

测试的时候需要另起一个线程去模拟第三方回调

引入ThreadPoolTaskExecutor类

  • 配置ThreadPoolTaskExecutor类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class ThreadPoolTaskConfig {


@Bean(name="threadPoolTaskExecutor")
public ThreadPoolTaskExecutor executor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//此方法返回可用处理器的虚拟机的最大数量; 不小于1
int core = Runtime.getRuntime().availableProcessors();
executor.setCorePoolSize(core);//设置核心线程数
executor.setMaxPoolSize(core*2 + 1);//设置最大线程数
executor.setKeepAliveSeconds(3);//除核心线程外的线程存活时间
executor.setQueueCapacity(40);//如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
executor.setThreadNamePrefix("thread-execute");//线程名称前缀
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//设置拒绝策略
return executor;
}
}
  • 使用ThreadPoolTaskExecutor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Autowired
private ThreadPoolTaskExecutor taskExecutor;

//10秒以后自动回调
taskExecutor.execute(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Map<String, String> requestData = new HashMap<>();
requestData.put("orderNo", providerResultDTO.getOrderNo());
requestData.put("providerOrderNo", providerResultDTO.getProviderOrderNo());
HttpClientUtil.post("http://localhost:8091/exchange/egift/exchange/rest/v_1/callback/10068", requestData);
});
赏个🍗吧
0%