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";
        }

posted on   荣锋亮  阅读(652)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-08-28 wso2 关于graphql 的方案
2020-08-28 Meeting Modern Business Needs with GraphQL
2018-08-28 prisma 服务器端订阅试用

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示