1.创建配置类
1.1.修改yml文件,配置线程池相关参数
async
:
corePoolSize
: 10
maxPoolSize
: 20
queueCapacity
: 300
keepAliveSeconds
: 60
threadNamePrefix
: do-rabbitMq
-push
1.2.创建线程池配置类
import org
.springframework
.beans
.factory
.annotation
.Value
;
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
;
@Configuration
@EnableAsync
public class AsyncConfiguration {
@Value("${async.corePoolSize}")
private Integer corePoolSize
;
@Value("${async.maxPoolSize}")
private Integer maxPoolSize
;
@Value("${async.queueCapacity}")
private Integer queueCapacity
;
@Value("${async.keepAliveSeconds}")
private Integer keepAliveSeconds
;
@Value("${async.threadNamePrefix}")
private String threadNamePrefix
;
@Bean("rabbitMqExecutor")
public Executor
rabbitMqExecutor() {
ThreadPoolTaskExecutor executor
= new ThreadPoolTaskExecutor();
executor
.setCorePoolSize(corePoolSize
);
executor
.setMaxPoolSize(maxPoolSize
);
executor
.setQueueCapacity(queueCapacity
);
executor
.setKeepAliveSeconds(keepAliveSeconds
);
executor
.setThreadNamePrefix(threadNamePrefix
);
executor
.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor
.initialize();
return executor
;
}
}
1.3在对应的方法上添加注解@Async(“rabbitMqExecutor”)
@Async("rabbitMqExecutor")
public void pushMqProductByIdsAsync(List
<String> ids
) {
if (CollectionUtils
.isEmpty(ids
)) {
return;
}
List
<Product> productList
= productMapper
.selectBatchIds(ids
);
for (Product product
: productList
) {
pushMqProduct(product
);
}
}
转载请注明原文地址:https://tech.qufami.com/read-15794.html