源基础上导入 pom 依赖
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>2.6.0</version>
</dependency>
创建流对象
package com.fang.stream;
import org.apache.kafka.clients.admin.NewTopic;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* @Author Mr. Sun.
* @Date 2020-11-10 8:48
*/
@Component
public class KafkaStream {
@Bean
public KStream<String, String> kStream(StreamsBuilder streamsBuilder){
KStream<String, String> stream = streamsBuilder.stream("Stream");
// 有兴趣可以写个 wordCount
stream.map((key,value) -> {
value+="--test--";
return new KeyValue<>(key,value);
}).to("AnotherTopic");
return stream;
}
}
监听出口
package com.fang.stream;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
/**
* @Author Mr. Sun.
* @Date 2020-11-10 9:22
*/
@Component
public class KafkaStreamListener {
@KafkaListener(topics = "AnotherTopic")
public void onMessage1(String message) {
// 处理
System.out.println("Stream处理之后的"+message);
}
@KafkaListener(topics = "Stream")
public void onMessage2(String message) {
// 处理
System.out.println("Stream处理之前的"+message);
}
}
测试
@RequestMapping("/streams")
public String sendMessageStreams(){
kafkaTemplate.send("Stream","key1","你好1");
return "success";
}