java - 如何在 Drools 中处理动态 Json/类?

标签 java drools rule-engine

我正在编写一个 RESTful 服务来根据某些规则计算某些值。

例如:

有一个这样的 JSON:

{ "amount": 100,
  "destination":"A"
}

此数据是请求正文,发布到我的 Controller :

@RequestMapping(value = "/orders", method= RequestMethod.POST)
public void getOrderRequest(@RequestBody Order order){

// use Drools to calculate and return the result

}

这是实体类:

public class Order{
    private Integer amount;
    private String destination;
    private Float price;
    // getters and setters
}

我使用Drools计算价格(假代码):

package rules
import entity.Order
rule "rule1"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(amount <= 50 && destination=="A") 
    then
        $s.setPrice(1000);
        update($s);

rule "rule2"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(amount > 50 && destination=="A") 
    then
        $s.setPrice(2000);
        update($s);

这工作正常。所有规则都可以更改并运行,而无需重新启动我的 REST 服务。

这是一个场景,一个新字段添加到订单 JSON 中:

{ "amount": 100,
  "destination":"A",
  "customer":"Trump"
}

添加新规则: 如果客户是特朗普,则价格加倍:

rule "rule3"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(customer == "Trump") 
    then
        $s.setPrice(price * 2);
        update($s);

但是我必须向我的 Order 类添加一个新变量并重新启动我的服务。

我想知道有什么方法可以在不重新启动我的 REST 服务的情况下实现它吗?

或者我可以使用其他 BRMS 动态处理 JSON 数据吗?

最佳答案

使用Map来携带所有订单详细信息:

public class Order{
    private Map<String, Object> fields;
    // getters and setters
}

如果您设法将 JSON 中的值添加到 Map 中,那么您可以像这样编写规则:

rule "rule3"
    no-loop true
    lock-on-active true
    salience 1
    when
        $s : Order(fields["customer"] == "Trump") 
    then
        $s.setPrice(price * 2);
        update($s);

关于java - 如何在 Drools 中处理动态 Json/类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53495152/

相关文章:

Ruby 和规则引擎

java 告诉找不到符号

java - Spring-Security:MySQL JDBC 身份验证失败

java - 禁止触发另一个流口水规则

具有显着性问题的 Drools 冲突解决程序

amazon-web-services - 如何使用 aws iot 规则引擎更新 dynamodb 的多列

java - Hibernate查询与SQL相比真的节省时间吗?

java - 如何清除 GWT 中的 RootPanel?

drools - 从 java Util 类中调用 drool 或静态方法中的 "function"哪个更好

c# - 我如何构建可以执行用户定义的规则引擎,如果在 C#.net 中有其他规则