Axon Framework 4.5.4调用EventStore.readEvents出现序列化异常问题
报错根因
org.axonframework.serialization.UnknownSerializedType 是Axon的占位类,触发场景是Axon从EventStore读取事件时,找不到对应事件类的全限定名定义,无法完成反序列化,就会用这个类包装原始序列化内容。
你配置的axon.serializer.*规则仅作用于Axon框架内部的事件读写逻辑,你自己业务层返回数据时使用的是Spring管理的序列化实例,和Axon的序列化实例是隔离的。当你要把包含UnknownSerializedType的集合返回给前端/其他服务时,无论是Jackson还是XStream都没有针对该类的默认序列化规则,就会抛出对应异常。
解决方案
方案1:校验事件类可用性
- 确认调用
readEvents的服务classpath下,存在所有已写入EventStore的事件类,且类的全限定名、字段结构和事件写入时完全一致 - 若为跨服务读写事件场景,需确保事件类在所有关联服务的定义完全一致,优先抽取事件类为公共依赖包引入所有服务
方案2:配置序列化兼容规则
如果业务场景允许返回反序列化失败的占位内容,可以给序列化工具加兼容配置:
Jackson配置
给Spring全局的ObjectMapper添加对应规则,注册如下Bean即可:
import com.fasterxml.jackson.databind.SerializationFeature; import org.axonframework.serialization.UnknownSerializedType; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer customizer() { return builder -> builder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS) .serializerByType(UnknownSerializedType.class, (serializer, type, jsonSerializerProvider) -> { serializer.writeNull(); // 也可自定义输出规则,比如输出原始序列化数据 }); } }
XStream配置
如果使用XStream作为序列化器,需要将UnknownSerializedType加入XStream的安全允许列表:
import com.thoughtworks.xstream.XStream; import org.axonframework.serialization.UnknownSerializedType; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class XStreamConfig { @Bean public XStream xStream() { XStream xStream = new XStream(); xStream.allowTypeHierarchy(UnknownSerializedType.class); // 补充其他XStream自定义配置 return xStream; } }
方案3:业务层过滤无效事件
在拿到EventStore返回的事件后先做类型校验,过滤掉反序列化失败的占位对象,避免后续序列化:
List<Object> events = eventStore.readEvents(aggregateId) .asStream() .map(EventMessage::getPayload) .filter(payload -> !(payload instanceof UnknownSerializedType)) .toList();
内容的提问来源于stack exchange,提问作者Bilgehan
相关产品推荐
相关产品推荐

