pom依赖
1
2
3
4
5
6
7
8
9
10
|
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>
0.10
.
2.0
</version>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>
1.2
.
0
.RELEASE</version>
</dependency>
|
.properties
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
|
##kafka配置
offsets.storage=kafka
###Global
spring.kafka.bootstrap-servers=
###about producer
spring.kafka.producer.acks=
1
spring.kafka.producer.batch-size=
100
spring.kafka.producer.buffer-memory=
33554432
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
###about consumer
spring.kafka.consumer.group-id=apply-test
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.enable-auto-commit=
true
spring.kafka.consumer.auto-commit-interval=
100
#spring.kafka.consumer.max-poll-records=
100
#spring.kafka.consumer.fetch-max-wait=
5000
#spring.kafka.consumer.fetch-min-size=
50
###about listener
spring.kafka.listener.concurrency=
3
spring.kafka.listener.pollTimeout=
3000
#spring.kafka.listener.ackMode=RECORD
#spring.kafka.listener.ackCount=
2
#spring.kafka.listener.ackTime=
1000
|
使用代码:
(1)以Producer为例,@Autowired KafkaTemplate即可发消息。(具体参考KafkaTemplate send方法)
1
2
3
4
5
6
7
|
@Autowired
private
KafkaTemplate<Integer, String> template;
public
void
processMessage() {
template.send(
"topic"
,
"message"
);
template.flush();
}
|
(2)以Consumer为例,在处理message的方法上打上@KafkaListener注解即可。
1
2
3
4
5
6
7
8
9
|
@KafkaListener
(topics =
"topic"
)
public
void
processMessage(String message) {
// do something consum the message
}
// @KafkaListener(topics = "topic")
// public void processMessages(ConsumerRecords records) {
// // do something consum the messages
// }
|