Kafka的条件接收

有时候,我们需要有针对性的接收一些消息,在之前的文章里我已经写过基于kafkaTemplate的消息组件。
Springboot集成Kafka完成消息回调,错误处理,消息拦截,批量处理

关于cloud stream又有了新的拦截方式。或者更形象的说是,按条件接收消息。
发送者:

public interface TestTopic {
    String OUTPUT2 = "example-topic-output3";
    @Output(OUTPUT2)
    MessageChannel output2();
}

public class TestController {
    @Autowired
    private TestTopic testTopic;
    @RequestMapping("test")
    public void Test1(@RequestParam String message){
     testTopic.output2().send(MessageBuilder.withPayload(message.toLowerCase()).setHeader("version","1.0").setHeader("haha","aaa").build());
    }
}
# 输出example-topic-output通道绑定的topic
spring.cloud.stream.bindings.example-topic-output2.destination=example-topic-two
spring.cloud.stream.bindings.example-topic-output3.destination=example-topic-three

消费者:

public interface TestTopic {
    String INPUT1 = "test-topic-input1";
    String ERRORINPUT1 = "errorChannel-input1";
    @Input(INPUT1)
    SubscribableChannel input1();
    @Input(ERRORINPUT1)
    SubscribableChannel errorInput1();
}

@Slf4j
@Component
@EnableBinding(TestTopic.class)
public class TestListener {

    @StreamListener(TestTopic.INPUT1)
    public void receive2(StreamMessage message) {
        log.info("receive2 payload : {}", message);
    }
    @StreamListener(value = TestTopic.INPUT2, condition = "headers['version']=='1.0'")
    public void receiveV1(String payload, @Header("version") String version) {
        log.info("Received v1 : " + payload + ", " + version);
    }
    @StreamListener(TestTopic.ERRORINPUT1)
    public void errorReceive1(StreamMessage message) {
        log.info("errorReceive1 payload : {}", message);
    }
}

这样子我们就可以通过@StreamListener(value = TestTopic.INPUT2, condition = "headers['version']=='1.0'")注解来指定接收什么消息。至于如何区分发送。则是在生产方:testTopic.output2().send(MessageBuilder.withPayload(message.toLowerCase()).setHeader("version","1.0").setHeader("haha","aaa").build());
注意接受条件:
condition可以少定条件,但不能多定条件,或条件错误,否则也是接收不到的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值