dongyukun
2024-12-31 0a2b23ad3f30dfb01c5d590fb98f39e93bfe1932
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.tenant.core.mq.kafka;
H 2
3 import cn.hutool.core.util.StrUtil;
4 import lombok.extern.slf4j.Slf4j;
5 import org.springframework.boot.SpringApplication;
6 import org.springframework.boot.env.EnvironmentPostProcessor;
7 import org.springframework.core.env.ConfigurableEnvironment;
8
9 /**
10  * 多租户的 Kafka 的 {@link EnvironmentPostProcessor} 实现类
11  *
12  * Kafka Producer 发送消息时,增加 {@link TenantKafkaProducerInterceptor} 拦截器
13  *
14  * @author iailab
15  */
16 @Slf4j
17 public class TenantKafkaEnvironmentPostProcessor implements EnvironmentPostProcessor {
18
19     private static final String PROPERTY_KEY_INTERCEPTOR_CLASSES = "spring.kafka.producer.properties.interceptor.classes";
20
21     @Override
22     public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
23         // 添加 TenantKafkaProducerInterceptor 拦截器
24         try {
25             String value = environment.getProperty(PROPERTY_KEY_INTERCEPTOR_CLASSES);
26             if (StrUtil.isEmpty(value)) {
27                 value = TenantKafkaProducerInterceptor.class.getName();
28             } else {
29                 value += "," + TenantKafkaProducerInterceptor.class.getName();
30             }
31             environment.getSystemProperties().put(PROPERTY_KEY_INTERCEPTOR_CLASSES, value);
32         } catch (NoClassDefFoundError ignore) {
33             // 如果触发 NoClassDefFoundError 异常,说明 TenantKafkaProducerInterceptor 类不存在,即没引入 kafka-spring 依赖
34         }
35     }
36
37 }