2 回答
TA贡献1982条经验 获得超2个赞
似乎我没有任何机会为相同的侦听器配置不同SERIALIZER| DESERIALIZERs。
但是 id 并不意味着我的问题没有解决方案。
我对所有对象都使用了继承,并提供了一个抽象AbstractEvent。AbstractEvent一般没用,但它在我的解决方案中使用,如指定的输入点SERIALIZER| DESERIALIZER. 为了获取上下文中哪个对象的信息,我使用了自定义标题。org.apache.kafka.common.serialization.Deserializer没有标题参数,但我已经实现了我的DESERIALIZER基于ExtendedDeserializer. 这种方式让我可以访问标题
via public T deserialize(String topic, Headers headers, byte[] data)
我的解串器示例:
@Slf4j
public class AbstractEventDeserializer<T extends AbstractEvent> implements ExtendedDeserializer<T> {
private Map<String, Class<T>> mappers = new HashMap<>();
// default behavior
@Override
public T deserialize(String arg0, byte[] devBytes) {
ObjectMapper mapper = new ObjectMapper();
T bar = null;
try {
bar = (T) mapper.readValue(devBytes, Bar.class);
} catch (Exception e) {
e.printStackTrace();
}
return bar;
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public T deserialize(String topic, Headers headers, byte[] data) {
log.info("handling...");
headers.forEach(header -> log.info(" {}: {}", header.key(), getHeaderValueAsString(header)));
Optional<String> classTypeFromHeader = getClassTypeFromHeader(headers);
if (classTypeFromHeader.isPresent()) {
return parseFromJson(data, mappers.get(classTypeFromHeader.get()));
}
return deserialize(topic, data);
}
private Optional<String> getClassTypeFromHeader(Headers headers) {
return StreamSupport.stream(headers.headers("X-CLASS-TYPE").spliterator(), false)
.map(Header::value)
.map(String::new)
.findFirst();
}
private String getHeaderValueAsString(Header header) {
return Optional.ofNullable(header.value())
.map(String::new)
.orElse(null);
}
@Override
public void configure(Map<String, ?> arg0, boolean arg1) {
log.info("configuring deserialiser");
if (arg0.containsKey("mappers")) {
this.mappers = (Map<String, Class<T>>) arg0.get("mappers");
}
arg0.keySet().forEach(key -> log.info(" {}:{}", key, arg0.get(key)));
}
}
如果您想尝试工作解决方案,请查看实验示例。
TA贡献1828条经验 获得超3个赞
Spring 云服务可以为消费者提供更好的配置、并发、反序列化和更少的样板代码。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
水槽样品
@SpringBootApplication
@EnableBinding(Sink.class)
public class LoggingConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(LoggingConsumerApplication.class, args);
}
@StreamListener(Sink.INPUT)
public void handle(Person person) {
System.out.println("Received: " + person);
}
public static class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
}
示例配置:
spring:
cloud:
stream:
bindings:
input:
destination: <your topic>
group: <your consumer group>
consumer:
headerMode: raw
partitioned: true
concurrency: 10
kafka:
binder:
brokers: <Comma seperated list of kafka brokers>
此处提供更多信息https://cloud.spring.io/spring-cloud-stream/
添加回答
举报