• 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";
            }
  • 相关阅读:
    火狐浏览器标签之间切换的快捷键
    LeetCode 69. x 的平方根
    LeetCode 51. N皇后
    win 10 自带 Ubuntu 系统的文件位置
    LeetCode 122. 买卖股票的最佳时机 II
    LeetCode 169. 求众数
    LeetCode 50. Pow(x, n)
    LeetCode 236. 二叉树的最近公共祖先
    LeetCode 235. 二叉搜索树的最近公共祖先
    LeetCode 98. 验证二叉搜索树
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/15201599.html
Copyright © 2020-2023  润新知