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可以少定条件,但不能多定条件,或条件错误,否则也是接收不到的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章