关于Spring.Kafka的使用

首先配置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内即可查看消费结果。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值