1.自定义线程池
package com.zyp.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author syl
* @description 配置线程池
* @since 2021/4/23
*/
@Configuration
@Slf4j
//开启异步
@EnableAsync
public class ThreadPoolConfig {
@Bean("threadPoolTaskExecutor")
public Executor getThreadPoolTaskExecutor(){
log.info("配置线程池----------------");
ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
//核心线程数
executor.setCorePoolSize(10);
//最大线程数
executor.setMaxPoolSize(50);
//队列容量
executor.setQueueCapacity(10);
//线程名前缀
executor.setThreadNamePrefix("taskExecutor-");
//线程池中corePoolSize线程空闲时间达到keepAliveTime是否关闭
executor.setAllowCoreThreadTimeOut(false);
//线程超时时间
executor.setKeepAliveSeconds(100);
//rejection-policy:当pool已经达到max size的时候,如何处理新任务
//CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
//对拒绝task的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//设置线程池关闭的时候是否等待所有任务都完成再继续销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
//该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁
// 以确保应用最后能够被关闭,而不是阻塞住。
executor.setAwaitTerminationSeconds(60);
//加载
executor.initialize();
return executor;
}
}
controller层
package com.zyp.controller;
import com.zyp.common.NoLogin;
import com.zyp.service.AsyncService;
import com.zyp.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* @author syl
* @description 线程池异步测试
* @since 2022/7/13
*/
@RestController
@RequestMapping("async")
@Api(tags = "线程池异步测试")
public class AsyncController {
@Autowired
private AsyncService asyncService;
@ApiOperation("线程池异步执行无返回值")
@GetMapping("test1")
@NoLogin
public Result test1(){
asyncService.executeAsync();
return Result.ok();
}
@ApiOperation("线程池异步执行有返回值")
@GetMapping("test2")
@NoLogin
public Result test2() throws ExecutionException, InterruptedException {
Future<String> future = asyncService.executeAsync1();
String s;
//获取到执行结果才返回
while (true) {
if (future.isDone()) {
s=future.get();
break;
}
}
return Result.ok(s);
}
}
Service层
package com.zyp.service;
import java.util.concurrent.Future;
/**
* @author syl
* @description 异步执行
* @since 2021/4/23
*/
public interface AsyncService {
/**
* 执行异步方法
*/
void executeAsync();
/**
* 执行异步方法
* @return
*/
Future<String> executeAsync1();
}
package com.zyp.service.impl;
import com.zyp.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
/**
* @author syl
* @description 异步执行实现类
* @since 2021/4/23
*/
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {
@Override
@Async("threadPoolTaskExecutor")
public void executeAsync() {
String name = Thread.currentThread().getName();
log.info("线程{}异步执行开始",name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("线程{}异步调用结束",name);
}
@Override
@Async("threadPoolTaskExecutor")
public Future<String> executeAsync1() {
String name = Thread.currentThread().getName();
log.info("线程{}异步执行开始",name);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("线程{}异步调用结束",name);
//用AsyncResult接收线程执行结果
return new AsyncResult<>("线程"+name+"执行结束");
}
}