异步多线程
程序员文章站
2022-07-10 18:38:07
...
线程池创建
背景:开通商品接口速度比较慢,所以异步去开通
配置线程池
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Log4j
@Configuration
@EnableAsync
public class OpenGoodsConfig {
private static final int THREADS = 4;
//核心线程数
private int corePoolSize = THREADS;
//线程池最大数量
private int maxPoolSize = 2 * THREADS;
//任务队列容量
private int queueCapacity = 1024;
//线程前缀
private String namePrefix = "async-openGoods-";
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
// -%d不要少
.setNameFormat(namePrefix + "%d")
.setDaemon(true)
.build();
/**
* @return
*/
@Bean(name = "asyncOpenGoodsExecutor")
public Executor asyncOpenGoodsExecutor() {
return new ThreadPoolExecutor(corePoolSize, maxPoolSize,
60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(queueCapacity),
threadFactory,
(r, executor) -> {
//打印日志,添加监控等
//拒绝操作,可以打印日志或者数据入库等。
// System.out.println("task is rejected!");
log.info("task is rejected!");
});
}
}
名词解释
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
@EnableAsync开始对异步任务的支持
任务类
public class OpenGoodsTask implements Runnable {
private GWYSelfHelpOpenReqDto helpOpenReqDto;
private final ILog logger = LoggerFactory.getLogger(this.getClass());
public OpenGoodsTask(GWYSelfHelpOpenReqDto helpOpenReqDto, ManageTenantOrder tenantOrder, String creater, OpenSassGoodService openSassGoodService) {
this.helpOpenReqDto = helpOpenReqDto;
}
@Override
public void run() {
logger.info("开始运行发送任务");
//doSomethings
}
}
@Autowired
private Executor asyncOpenGoodsExecutor;
//异步开通商品
OpenGoodsTask goodsTask = new OpenGoodsTask(openReqDto);
asyncOpenGoodsExecutor.execute(goodsTask);
上一篇: 斗地主模拟Java