-
pom引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-stream-kafka</artifactId> </dependency>
-
配置文件增加相关配置
spring: cloud: stream: kafka: binder: // 主动创建topic auto-create-topics: true // kafka服务端 brokers: ip:端口 default-binder: kafka bindings: # 绑定消费key key-input: consumer: concurrency: 1 content-type: text/plain #消息格式 destination: orange #消息的目的地 group: resource # 绑定输入key key-output: destination: orange #消息的目的地
-
定义提供者、接收者interface
/** * @Description: 提供者输出 */ public interface KeySource { String KEY_OUTPUT = "key-output"; /** * 定义输出Channel * * @return channel */ @Output(KeySource.KEY_OUTPUT) SubscribableChannel keyOutput(); } /** * @Description: 接收者输入 */ public interface KeySink { String KEY_INPUT = "key-input"; /** * 定义输入Channel * * @return channel */ @Input(KeySink.KEY_INPUT) SubscribableChannel keyInput(); }
-
Source调用发送消息
@Component @EnableBinding(KeySource.class) @Slf4j public class KafkaProducerService { @Autowired private KeySource keySource; public void sendMsg(JSONObject myObj) { log.info("provider发送test消息: {}", myObj); keySource.keyOutput().send(MessageBuilder.withPayload(myObject).build()); } }
-
Sink接收消息、@StreamListener
@Component @Slf4j // 绑定接收者 @EnableBinding({KeySink.class}) public class KafkaConsumerService { @StreamListener(KeySink.KEY_INPUT) public void receiveMsg(JSONObject myObj) { log.info("consumer接收到消息:{}", JSON.toJSONString(myObj)); // xxx 业务代码 } }
kafka 使用
于 2022-04-27 19:06:35 首次发布