配置文件

1
2
3
4
5
6
7
8
9
10
spring.kafka.wh.bootstrap-servers=192.168.1.130:9092,192.168.1.130:9093
spring.kafka.wh.consumer.group-id=kafka_demo
spring.kafka.wh.consumer.enable-auto-commit=false
spring.kafka.es.consumer.auto-offset-reset=latest

spring.kafka.es.bootstrap-servers=192.168.1.130:9094
spring.kafka.es.consumer.group-id=kafka_demo
spring.kafka.es.consumer.enable-auto-commit=false
spring.kafka.es.consumer.auto-offset-reset=latest
log-topic-name=test

KafkaWhConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaWhConfig {

@Value("${spring.kafka.wh.bootstrap-servers}")
private String bootstrapServers;
@Value("${spring.kafka.wh.consumer.group-id}")
private String groupId;
@Value("${spring.kafka.wh.consumer.enable-auto-commit}")
private boolean enableAutoCommit;
@Value("${spring.kafka.wh.consumer.auto-offset-reset}")
private String autoOffsetReset;

@Bean(name = "kafkaWhTemplate")
public KafkaTemplate<String, String> kafkaWhTemplate() {
return new KafkaTemplate<>(producerFactory());
}

@Bean(name = "kafkaWhContainerFactory")
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> kafkaWhContainerFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(3);
//Listener配置
factory.getContainerProperties()
.setPollTimeout(3000);
factory.getContainerProperties()
.setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
factory.getContainerProperties()
.setPollTimeout(15000);
return factory;
}

private ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(producerConfigs());
}

public ConsumerFactory<Integer, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}

private Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.RETRIES_CONFIG, 10);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 1000);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}

private Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
return props;
}
}

KafkaEsConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListenerConfigurer;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerConfigUtils;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.*;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import org.springframework.kafka.listener.ContainerProperties;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaEsConfig {


@Value("${spring.kafka.es.bootstrap-servers}")
private String bootstrapServers;
@Value("${spring.kafka.es.consumer.group-id}")
private String groupId;
@Value("${spring.kafka.es.consumer.enable-auto-commit}")
private boolean enableAutoCommit;
@Value("${spring.kafka.es.consumer.auto-offset-reset}")
private String autoOffsetReset;

@Bean(name = "kafkaEsTemplate")
public KafkaTemplate<String, String> kafkaEsTemplate() {
return new KafkaTemplate<>(producerFactory());
}

@Bean(name = "kafkaEsContainerFactory")
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<Integer, String>> kafkaEsContainerFactory() {
ConcurrentKafkaListenerContainerFactory<Integer, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(3);
//Listener配置
factory.getContainerProperties()
.setPollTimeout(3000);
factory.getContainerProperties()
.setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE);
factory.getContainerProperties()
.setPollTimeout(15000);
return factory;
}

private ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(producerConfigs());
}

public ConsumerFactory<Integer, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}

private Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.RETRIES_CONFIG, 10);
props.put(ProducerConfig.ACKS_CONFIG, "all");
props.put(ProducerConfig.BATCH_SIZE_CONFIG, 1000);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}

private Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, 1000);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
return props;
}
}

前置动态处理DataSourceHolder【利用Interceptor + reqHeader】

CityEnum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum CityEnum {
/*武汉*/
wuhan("wuhan"),
/*恩施*/
enshi("enshi");

private String city;

CityEnum(String city) {
this.city = city;
}

public String getCity() {
return city;
}
}

DataSourceHolder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class DataSourceHolder {
//线程本地环境
private static final ThreadLocal<String> contextHolders = new ThreadLocal<>();

//设置数据源
public static void setDataSource(String customerType) {
contextHolders.set(customerType);
}

//获取数据源
public static String getDataSource() {
return contextHolders.get();
}

//清除数据源
public static void clearDataSource() {
contextHolders.remove();
}
}

DynamicDataSourceInterceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author best
*/
@Component
public class DynamicDataSourceInterceptor implements HandlerInterceptor {

//在业务处理器处理请求之前被调用
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String city = request.getHeader("city");
if (StringUtils.isBlank(city)) {
city = CityEnum.wuhan.getCity();
}
DataSourceHolder.setDataSource(city);
//RequestCityHolder.add(city);
System.err.println(city + "处理开始...");
return true;
}

//请求完成之后
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
String city = request.getHeader("city");
if (StringUtils.isBlank(city)) {
city = CityEnum.wuhan.getCity();
}
//清除数据源
DataSourceHolder.clearDataSource();
//清除ThreadLocal变量
//RequestCityHolder.remove();
System.err.println(city + "处理完成...");
}
}

KafkaSendUtil

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

@Component
public class KafkaSendUtil {
private static KafkaTemplate kafkaWhTemplate;

private static KafkaTemplate kafkaEsTemplate;

@Autowired
public KafkaSendUtil(@Qualifier("kafkaWhTemplate") KafkaTemplate kafkaWhTemplate,
@Qualifier("kafkaEsTemplate") KafkaTemplate kafkaEsTemplate) {
KafkaSendUtil.kafkaWhTemplate = kafkaWhTemplate;
KafkaSendUtil.kafkaEsTemplate = kafkaEsTemplate;
}

public static ListenableFuture send(String topic, String type, String msg) {
String city = DataSourceHolder.getDataSource();
ListenableFuture listenableFuture = null;
switch (CityEnum.valueOf(city)) {
case wuhan:
listenableFuture = kafkaWhTemplate.send(topic, type, msg);
break;
case enshi:
listenableFuture = kafkaEsTemplate.send(topic, type, msg);
break;
default:
break;
}
return listenableFuture;
}
}

KafkaConsumer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

@Component
public class KafkaConsumer {

private static final Logger LOGGER = LoggerFactory.getLogger(KafkaConsumer.class);

// containerFactory 的值要与配置中 KafkaListenerContainerFactory 的 Bean 名相同
@KafkaListener(topics = {"#{'${log-topic-name}'.split(',')}"}, containerFactory = "kafkaWhContainerFactory")
public void listenerOne(ConsumerRecord<?, ?> record, Acknowledgment ack) {
LOGGER.info(" kafka wuhan 消费者 接收到消息:{}", record.toString());
ack.acknowledge();
}

@KafkaListener(topics = {"#{'${log-topic-name}'.split(',')}"}, containerFactory = "kafkaEsContainerFactory")
public void listenerTwo(ConsumerRecord<?, ?> record, Acknowledgment ack) {
LOGGER.info(" kafka enshi 消费者 接收到消息:{}", record.toString());
ack.acknowledge();
}
}