Spring Boot配置多线程(创建线程池、创建线程)
1 Maven依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2 AsyncConfig
多线程配置类。
package com.config;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
/**
* 多线程配置类
*/
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfig(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
/**
* 创建线程池
*
* @return
*/
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
//设置最大线程数
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
//线程池所使用的缓冲队列
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
// 线程名称前缀
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
public static class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
InitializingBean, DisposableBean {
static final String EXCEPTION_MESSAGE = "Caught async exception";
private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);
private final AsyncTaskExecutor executor;
/**
* <p>Constructor for ExceptionHandlingAsyncTaskExecutor.</p>
*
* @param executor a {@link AsyncTaskExecutor} object.
*/
public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
this.executor = executor;
}
/**
* {@inheritDoc}
*/
@Override
public void execute(Runnable task) {
executor.execute(createWrappedRunnable(task));
}
/**
* {@inheritDoc}
*/
@Override
public void execute(Runnable task, long startTimeout) {
executor.execute(createWrappedRunnable(task), startTimeout);
}
private <T> Callable<T> createCallable(final Callable<T> task) {
return () -> {
try {
return task.call();
} catch (Exception e) {
handle(e);
throw e;
}
};
}
private Runnable createWrappedRunnable(final Runnable task) {
return () -> {
try {
task.run();
} catch (Exception e) {
handle(e);
}
};
}
/**
* <p>handle.</p>
*
* @param e a {@link Exception} object.
*/
protected void handle(Exception e) {
log.error(EXCEPTION_MESSAGE, e);
}
/**
* {@inheritDoc}
*/
@Override
public Future<?> submit(Runnable task) {
return executor.submit(createWrappedRunnable(task));
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> submit(Callable<T> task) {
return executor.submit(createCallable(task));
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() throws Exception {
if (executor instanceof DisposableBean) {
DisposableBean bean = (DisposableBean) executor;
bean.destroy();
}
}
/**
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet() throws Exception {
if (executor instanceof InitializingBean) {
InitializingBean bean = (InitializingBean) executor;
bean.afterPropertiesSet();
}
}
}
}
3 AsyncTestService
声明异步方法。
package com.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTestService {
@Async
public void test(int num) {
System.out.print("\tnum=" + num);
}
}
4 调试代码
package com.controller;
import com.service.AsyncTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
private AsyncTestService asyncTestService;
/**
* 测试多线程
*/
@GetMapping("/testAsync")
public void testAsync() {
for (int i = 0; i < 100; i++) {
System.out.print("\ti=" + i);
}
for (int j = 0; j < 100; j++) {
asyncTestService.test(j);
}
System.out.print("i=" + 1111);
}
}
5 调试结果
注:
有关调用异步方法创建线程的方式请查看以下博客。
Java 调用@Async异步方法创建线程2种方式(调用外部的异步方法,调用内部的异步方法)_旭东怪的博客-CSDN博客1 Maven依赖 https://blog.csdn.net/qq\_38974638/article/details/120348519
还没有评论,来说两句吧...