easy-rules facts 添加扩展数据

一个很常见的场景,我们希望在easy-rules 的facts 中添加一些扩展数据(比如json)
但是因为默认facts 是会进行数据转map的,很多时候可能不会产生我们希望的结果

解决方法

包装一个新的对象,在执行rule 的时候在facts 传递一个初始对象,然后就可以使用引用的模式使用数据了
rule 文件定义中对于spel 的需要使用#,对于代码定义的rule 可以使用注解

参考

一个rule 集成jmeshpath的demo
spring bean

 
package com.dalong.rule;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.burt.jmespath.Expression;
import io.burt.jmespath.JmesPath;
import io.burt.jmespath.jackson.JacksonRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component("myService")
public class MyService {
    private static  JmesPath<JsonNode> jmespath = new JacksonRuntime();
    @Autowired
    private ObjectMapper ob;
   public  User setInfo(User biz) {
       System.out.println("call bean method");
       System.out.println(biz.toString());
       biz.setAge(4444);
       biz.setUniqueId("4444");
       return  biz;
   }
 
  // 此处可以改写MyResult
    public  void setInfo2(User biz,MyResult result,String query) {
        System.out.println("call bean setInfo2 method");
        System.out.println(biz.toString());
        biz.setUniqueId("5555");
        Expression<JsonNode> expression = jmespath.compile(query);
        JsonNode input =  ob.valueToTree(biz);
        JsonNode myresult = expression.search(input);
        System.out.println(myresult.toString());
        result.setJsonNode(myresult);
    }
}
 

执行rule

 rules.register(new MyRule());
        Facts facts = new Facts();
        // 生成一个唯一id,方便基于数据id规则流程查询
        facts.put("biz",cloudEventData.getValue());
        facts.put("result",new MyResult()); // 初始对象
        rulesEngine.fire(rules,facts);
        Object userResult=  facts.get("biz");
        MyResult result  =facts.get("result"); // spring bean 可以修改此数据,然后重新获取
        if(Objects.isNull(result.getJsonNode())){
            return  "not  execute";
        }
原文地址:https://www.cnblogs.com/rongfengliang/p/15201599.html