Drools Engine 8.29.0.Final中KieBase序列化失败问题求助
问题本质
SessionsAwareKnowledgeBase实现的KieBase接口本身未实现Serializable接口,直接进行Java原生序列化必然失败,这就是你无法将KieBase序列化存入数据库的核心原因。
可行解决方案
方案1:用Drools内置Marshaller序列化KieBase
Drools官方提供了KieMarshallers工具专门处理KieBase和KieSession的持久化,能适配Drools内部规则结构,比原生序列化更可靠。
示例代码:
// 序列化KieBase为字节数组 KieServices kieServices = KieServices.Factory.get(); KieMarshaller marshaller = kieServices.getMarshallers().newKieMarshaller(kieBase.getKieContainer()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshall(baos, kieBase); byte[] kieBaseBytes = baos.toByteArray(); // 将kieBaseBytes存入数据库的BLOB字段 // 从数据库读取并反序列化 byte[] storedBytes = // 从数据库取出的字节数组 ByteArrayInputStream bais = new ByteArrayInputStream(storedBytes); KieBase restoredKieBase = marshaller.unmarshall(bais);
方案2:优化KieSession持久化流程
如果你需要同时处理KieSession的持久化,需注意:
- 序列化KieSession同样使用Drools的Marshaller,而非原生序列化
- 反序列化KieSession前,必须先通过方案1恢复对应的KieBase,再用该KieBase创建Marshaller解组KieSession:
// 序列化KieSession KieSession kieSession = kieBase.newKieSession(); ByteArrayOutputStream sessionBaos = new ByteArrayOutputStream(); marshaller.marshall(sessionBaos, kieSession); byte[] sessionBytes = sessionBaos.toByteArray(); // 存入数据库 // 反序列化KieSession KieBase restoredKieBase = // 先恢复KieBase KieMarshaller sessionMarshaller = kieServices.getMarshallers().newKieMarshaller(restoredKieBase.getKieContainer()); ByteArrayInputStream sessionBais = new ByteArrayInputStream(sessionBytes); KieSession restoredSession = sessionMarshaller.unmarshall(sessionBais);
额外提示
- 序列化和反序列化时需保持Drools版本一致,避免版本不兼容导致失败
- 数据库存储字段建议用
BLOB类型存放字节数组
内容的提问来源于stack exchange,提问作者Naveen Reddy
相关产品推荐
相关产品推荐

