赞
踩
Apache Kafka以Topic为导向,提供消息中间件的功能。一个类型的数据称之为一个Topic。
使用docker compose安装Apache Kafka。
stack.yml
version: '3.1'
services:
zookeeper:
image: wurstmeister/zookeeper
restart: always
kafka:
image: wurstmeister/kafka
ports:
- "9092:9092"
environment:
KAFKA_ADVERTISED_HOST_NAME: localhost
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
执行命令:
$ docker-compose -f stack.yml up -d
新建应用,信息如下:
Group:top.wisely
Artifact:learning-kafka
Dependencies:Spring for Kafka
、Lombok
build.gradle
文件中的依赖如下:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.kafka:spring-kafka'
implementation 'com.fasterxml.jackson.core:jackson-databind' //消息序列化、反序列化使用
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
//...
}
Spring Boot给我们提供的自动配置为:KafkaAutoConfiguration
,它所做的自动配置有:
kafkaTemplate
;kafkaAdmin
的Bean用来在应用中新建Topic;@EnableKafka
注解开启Kafka的支持;通过KafkaProperties
使用spring.kafka.*
来配置Kafka。
连接Kafka并配置
spring:
kafka:
bootstrap-servers: #1
- localhost:9092
producer: # 2
# key-serializer: org.springframework.kafka.support.serializer.JsonSerializer #3
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer #4
consumer: #5
# key-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer #6
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer #7
group-id: consumers #8
properties:
spring:
json:
trusted:
packages: top.wisely.learningkafka.messaging #9
StringSerializer
,本例的Key为String类型,可省略;StringDeserializer
,符合默认,可省略;group-id
,若多个应用的消费者的group-id
相同可负载消费消息;top.wisely.learningkafka.messaging
加入消费者信任的发序列化包中。消息定义
@Data
@AllArgsConstru
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。