在kafka中有的时候我们在进行流处理时可能会遇到一些不符合流处理逻辑的数据,而这些数据如果进入到流处理中可能会出现异常,所以我们在进行流处理之前可以先对读取的流数据进行预判断,如果是异常数据,就直接放到异常topic中。
1.创建三个topic:
wyh-in是读取数据的topic,
wyh-out是正常的数据经过流处理之后进入的topic,
wyh-exc是异常数据进入的topic
2.创建项目,编写pom文件:
<dependencies>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-streams</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
3.代码实现:
package branch;
import iava.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.KStream;
public class KafkaBranch{
public static void main(string[]args){
//set topics
string inputTopic = "wyh-in";
string successTopic = "wyh-out";
string failureTopic = "wyh-exc";
Properties properties=new Properties();
properties.put("bootstrap.servers", "192.168.184.128:9092");
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "wyh-application");
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> source = builder.stream(inputTopic);
@SuppressWarnings("unchecked")
KStream<String, String>[] sourceBranches = source.branch(
//遍历key-value
(key, value) -> {
//设置flag标识是否是有效数据
boolean flag = false;
//这里我们假设如果value中含有字母“a”就视为无效数据
if(value.contains("a")){
flag = true;
}
return flag;
},
(key, value) -> true
);
sourceBranches[0].to(failureTopic);
sourceBranches[1].to(successTopic);
final Topology topology = builder.build();
final KafkaStreams streams = new KafkaStreams(topology, properties);
streams.cleanUp();
streams.start();
Runtime().getRuntime().addShutdownHook(new Thead(streams::close));
}
}
4.向wyh-in中发送消息:
5.查看消费者:
wyh-out:
wyh-exc:
可以看到含有"a"的消息被放到了异常的topic中。