我正在尝试扩展 Shop 教程以获得简单的规则 (shop) 以在多个 facts
上运行。在规则中编写条件时,我们使用“事实名称”调用函数,如下所示,
condition: "people.isAdult() == false"
因为people
只是facts
中一个对象实例的名字,像上面这样定义条件是不好的。我如何定义条件,使其遍历多个 facts
。
我想要实现的是在规则引擎的一次点火中评估多个事实的规则。
当将一组具有相同事实名称的事实提供给规则引擎时,仅评估最后提供的一个。但是,当为每个事实分配不同的名称时,我无法为每个事实分配相同的条件。
下面是代码。假设 Person
类对所有成员都有基本的 get/set 函数。
规则.yml:
---
name: "regex"
description: "Check if regex pattern matches"
priority: 1
condition: "people.getPayload().matches(\".*12.*34$\") == true"
actions:
- "System.out.println(\"There is a match\");"
---
name: "age"
description: "Check if person's age is > 18 and marks the person as adult"
priority: 2
condition: "people.age > 18"
actions:
- "people.setAdult(true);"
---
name: "alkol"
description: "children are not allowed to buy alcohol"
priority: 3
condition: "people.isAdult() == false"
actions:
- "System.out.println(\"Shop: Sorry, you are not allowed to buy portakal\");"
主要:
//create a person instance (fact)
Person [] PeopleArray = new Person [100];
Person [] KidsArray = new Person [300];
// initialize arrays
for(int i = 0; i < PeopleArray.length ; i++)
{
PeopleArray[i] = new Person("TOM"+i,23);
PeopleArray[i].setPayload(dummystring);
}
for(int i = 0; i < KidsArray.length ; i++)
{
KidsArray[i] = new Person("EMRE"+i,13);
KidsArray[i].setPayload(dummystring);
}
Facts facts = new Facts();
// create a rule set
Rules rules = MVELRuleFactory.createRulesFrom(new FileReader("rules.yml"));
RulesEngine rulesEngine = new DefaultRulesEngine();
System.out.println("Tom: Hi! can I have some Vodka please?");
//put the facts
for(int i = 0; i < PeopleArray.length ; i++)
facts.put("people", PeopleArray[i]);
long start = System.currentTimeMillis();
for(int i = 0; i < KidsArray.length ; i++)
facts.put("people", KidsArray[i]);
rulesEngine.fire(rules, facts);
最佳答案
Facts
对象本质上是一个 hashmap。因此,根据设计,您不能将两个事实放在同一个键上。
我在您的示例中看到 people
事实是一个数组。现在如何在 mvel 表达式中处理数组是另一回事了。老实说,我能给出的最佳答案是查看 MVEL 文档:https://github.com/imona/tutorial/wiki/MVEL-Guide#arrays
What I want to achieve is evaluate the rules on multiple facts in one fire of the rule engine.
我不确定这是否可以通过简单的规则实现。我认为你可以:
- 要么平面化你的事实
- 或者根据不同的事实多次调用
fire
希望这对您有所帮助。
关于java - Easy-Rules 规则引擎,不能同时触发多个事实,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50098634/