在Spring异步线程池中自动传递上下文,这样写轻松又方便

问题

在我们的日常开发中,可以通过@Async注解,很方便地启动一个异步线程。

比如现在有一个用户注册成功后,发送欢迎邮件的需求,在用户注册成功以后,便可以启动一个异步线程,在这个线程中调用邮件服务给用户发消息。

这样,即使邮件服务出了问题,也不会影响到当前用户的注册体验。

问题在于,异步线程无法获取原线程的数据信息,如果每次通过手写参数传递又会比较麻烦,所以我们希望通过某种形式,让数据可以自动传递给子线程。

解决方案

1,新建一个类,重写TaskDecorator类的decorate的方法

public class MDCContextDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        //RequestAttributes context = RequestContextHolder.currentRequestAttributes();
        //这里获取是mdc的上下文,也可以获取RequestContextHolder,具体根据你的业务需要操作即可
        Map<String,String> previous = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (previous != null) {
                    MDC.setContextMap(previous);
                }
                runnable.run();
            } finally {
              //务必记得clear,否则可能会产生内存泄露
                MDC.clear();
            }
        };
    }
}

2,在自定义的线程池中设置我们的自定义装饰器

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(20);
        // 设置最大线程数
        executor.setMaxPoolSize(30);
        // 设置队列容量
        executor.setQueueCapacity(1000);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("job-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池  全局线程池不能关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置我们自定义的Decorator
        executor.setTaskDecorator(new MDCContextDecorator());
        return executor;
    }

原理探究

Spring给我们预留一个任务装饰器TaskDecorator,通过这个任务装饰器,可以像AOP一样,对线程做一些功能增强。

在ThreadPoolTaskExecutor的源码中,initializeExecutor方法对线程池进行初始化,会判断是否有装饰器的实现。

protected ExecutorService initializeExecutor(
			ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
		
    BlockingQueue<Runnable> queue = createQueue(this.queueCapacity);
		ThreadPoolExecutor executor;
		if (this.taskDecorator != null) {
                          //如果进行了装饰,就转而去执行自定义的装饰方法
			  executor = new ThreadPoolExecutor(this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
					queue, threadFactory, rejectedExecutionHandler) {
				@Override
				public void execute(Runnable command) {
					Runnable decorated = taskDecorator.decorate(command);
					if (decorated != command) {
						decoratedTaskMap.put(decorated, command);
					}
					super.execute(decorated);
				}
			};
		}
		else {
			executor = new ThreadPoolExecutor(
					this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS,
					queue, threadFactory, rejectedExecutionHandler);

		}
		if (this.allowCoreThreadTimeOut) {
			executor.allowCoreThreadTimeOut(true);
		}
		this.threadPoolExecutor = executor;
		return executor;
	}

总结

利用ThreadPoolTaskExecutor的TaskDecorator,动态的给一个对象添加一些额外的功能,比生成子类会更加灵活。在我们平常的编码过程中,也建议大家尝试使用装饰模式优化我们的代码。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 在Spring Boot,我们可以通过自定义异步线程池来优化应用程序的性能。下面是一个简单的示例,演示如何在Spring Boot应用程序自定义异步线程池: 1. 首先,我们需要在Spring Boot应用程序的配置文件定义异步线程池的属性: ``` spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=1000 ``` 上述配置定义了异步线程池的核心大小、最大大小和队列容量。 2. 然后,我们需要创建一个自定义的异步线程池配置类,如下所示: ``` @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(1000); executor.setThreadNamePrefix("MyCustomExecutor-"); executor.initialize(); return executor; } } ``` 上述配置类实现了AsyncConfigurer接口,并覆盖了getAsyncExecutor()方法,该方法返回一个自定义的ThreadPoolTaskExecutor对象,其设置了异步线程池的核心大小、最大大小、队列容量和线程名称前缀。 3. 最后,在需要异步执行的方法上添加@Async注解即可: ``` @Service public class MyService { @Async public void doSomethingAsync() { // 异步执行的代码 } } ``` 上述示例,我们在MyService类的doSomethingAsync()方法上添加了@Async注解,表示该方法需要异步执行。 这样,我们就成功地自定义了Spring Boot应用程序异步线程池。 ### 回答2: 在Spring Boot,可以通过配置来自定义异步线程池。我们可以利用`@EnableAsync`注解开启异步支持,并使用`@Async`注解来标识需要异步执行的方法。 首先,在Spring Boot的配置文件(如application.properties或application.yml)配置线程池的相关属性,例如线程池核心线程数、最大线程数、队列容量等。示例配置如下: ``` spring.task.execution.pool.core-size=10 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=100 ``` 接下来,在启动类上添加`@EnableAsync`注解,以开启异步支持。例如: ```java @SpringBootApplication @EnableAsync public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 然后,我们可以在需要异步执行的方法上添加`@Async`注解,以告知Spring该方法需要异步执行。例如: ```java @Service public class MyService { @Async public void asyncMethod() { // 异步执行的方法体 } } ``` 在上述示例,`asyncMethod()`方法会被Spring框架异步执行,Spring自动线程池获取一个线程来执行该方法。 通过以上步骤,我们就可以在Spring Boot自定义异步线程池。我们可以根据具体的业务需求来调整线程池的配置,以达到最佳的性能和资源利用效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员拾山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值