首先配置application.properties
这里要在application里配置Kafka的ip,端口等;
指定默认消费者group id --> 由于在kafka中,同一组中的consumer不会读取到同一个消息,依靠groud.id设置组名
spring.kafka.consumer.group-id = test
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.enable-auto-commit=true
新建SpringBoot项目,pom里需要的配置,这里配置了测试用的redis
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId> <!--默认2.2.x-->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
<!-- redis客户端 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>`
简单使用如下,使用@KafkaListener注解
@SpringBootApplication
public class DemoApplication {
@KafkaListener(topics = "result")
public void onMessage(String message) throws Exception {
int typeA = 0, typeB = 0;
JSONArray jsonArray = JSON.parseArray(message);
JSONObject jsonObject;
jsonObject = JSON.parseObject(jsonArray.get(i).toString());
if (jsonObject.containsKey("0"))
typeA = jsonObject.getIntValue("0");
else if (jsonObject.containsKey("1"))
typeB = jsonObject.getIntValue("1");
RedisUtils redis = new RedisUtils();
redis.set("result", typeA + "," + typeB);
}
RedisUtils是自行封装的Redis的工具类,set保存类型为string;、
启动应用后,通过脚本生产topic为result的消息,在redis内即可查看消费结果。