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可以少定條件,但不能多定條件,或條件錯誤,否則也是接收不到的。

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