我正在使用 Spring Kafka 集成,并且我有自己的值通用序列化器/反序列化器,如下所示
序列化器:
public class KafkaSerializer<T> implements Serializer<T> {
private ObjectMapper mapper;
@Override
public void close() {
}
@Override
public void configure(final Map<String, ?> settings, final boolean isKey) {
mapper = new ObjectMapper();
}
@Override
public byte[] serialize(final String topic, final T object) {
try {
return mapper.writeValueAsBytes(object);
} catch (final JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
}
解串器:
public class KafkaDeserializer<T> implements Deserializer<T> {
private ObjectMapper mapper;
@Override
public void close() {
}
@Override
public void configure(final Map<String, ?> settings, final boolean isKey) {
mapper = new ObjectMapper();
}
@Override
public T deserialize(final String topic, final byte[] bytes) {
try {
return mapper.readValue(bytes, new TypeReference<T>() {
});
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
}
}
序列化程序运行良好,但是在消费消息时对值进行反序列化时,我得到的是一个LinkedHashMap
而不是期望的对象,请告诉我我在哪里弄错了,在此先感谢。