Spring Cloud Stream是否可以使用ReplyingKafkaTemplate
?要使用配置,是否有任何代码示例?
答案 0 :(得分:1)
这一切都在一个应用程序中,但说明了它是如何工作的...
@SpringBootApplication
@EnableBinding(Processor.class)
public class So57380643Application {
public static void main(String[] args) {
SpringApplication.run(So57380643Application.class, args).close();
}
@Bean
public ReplyingKafkaTemplate<byte[], byte[], byte[]> replyer(ProducerFactory<byte[], byte[]> pf,
ConcurrentMessageListenerContainer<byte[], byte[]> replyContainer) {
return new ReplyingKafkaTemplate<>(pf, replyContainer);
}
@Bean
public ConcurrentMessageListenerContainer<byte[], byte[]> replyContainer(
ConcurrentKafkaListenerContainerFactory<byte[], byte[]> factory) {
ConcurrentMessageListenerContainer<byte[], byte[]> container = factory.createContainer("replyTopic");
container.getContainerProperties().setGroupId("replies.group");
return container;
}
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public String listen(String in) {
return in.toUpperCase();
}
@Bean
public ApplicationRunner runner(ReplyingKafkaTemplate<byte[], byte[], byte[]> replyer) {
return args -> {
ProducerRecord<byte[], byte[]> record = new ProducerRecord<>("requestTopic", "foo".getBytes());
RequestReplyFuture<byte[], byte[], byte[]> future = replyer.sendAndReceive(record);
RecordMetadata meta = future.getSendFuture().get(10, TimeUnit.SECONDS).getRecordMetadata();
System.out.println(meta);
ConsumerRecord<byte[], byte[]> consumerRecord = future.get(10, TimeUnit.SECONDS);
System.out.println(new String(consumerRecord.value()));
};
}
}
和
spring:
kafka:
consumer:
enable-auto-commit: false
auto-offset-reset: earliest
cloud:
stream:
bindings:
input:
destination: requestTopic
group: so57380643
output:
destination: replyTopic
结果:
requestTopic-0@3
FOO