SpringCloud Executor,ExecutorService和ScheduledExecutorService

2023-12-02 11:39 更新

我们提供LazyTraceExecutorTraceableExecutorServiceTraceableScheduledExecutorService每次提交,调用或计划新任务时,这些实现都会创建spans。

以下示例显示了使用CompletableFuture时如何将跟踪信息传递给TraceableExecutorService

CompletableFuture<Long> completableFuture = CompletableFuture.supplyAsync(() -> {
	// perform some logic
	return 1_000_000L;
}, new TraceableExecutorService(beanFactory, executorService,
		// 'calculateTax' explicitly names the span - this param is optional
		"calculateTax"));

 Sleuth不适用于parallelStream()如果要使跟踪信息通过流传播,则必须使用supplyAsync(…​)的方法,如前所示。

如果有beans实现了您想从跨度创建中排除的Executor接口,则可以使用spring.sleuth.async.ignored-beans属性,在其中可以提供bean名称的列表。

定制执行者

有时,您需要设置AsyncExecutor的自定义实例。以下示例显示如何设置这样的自定义Executor

@Configuration
@EnableAutoConfiguration
@EnableAsync
// add the infrastructure role to ensure that the bean gets auto-proxied
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static class CustomExecutorConfig extends AsyncConfigurerSupport {

	@Autowired
	BeanFactory beanFactory;

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// CUSTOMIZE HERE
		executor.setCorePoolSize(7);
		executor.setMaxPoolSize(42);
		executor.setQueueCapacity(11);
		executor.setThreadNamePrefix("MyExecutor-");
		// DON'T FORGET TO INITIALIZE
		executor.initialize();
		return new LazyTraceExecutor(this.beanFactory, executor);
	}

}

 

为确保对配置进行后期处理,请记住在@Configuration类上添加@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号