我正在尝试扩展Shop Tutorial,以便在多个facts
上运行简单规则(shop)。在规则中写条件时,我们使用“事实名称”调用函数,如下所示,
condition: "people.isAdult() == false"
因为people
只是facts
中ONE对象实例的名称,所以定义上面的条件并不好。如何定义条件以使其迭代多个facts
。
我想要实现的是在规则引擎的一次火灾中评估多个事实的规则。
当向规则引擎提供具有相同事实名称的事实数组时,仅评估提供的最后一个事实。但是,当为每个事实分配不同的名称时,我不能为每个事实分配相同的条件。
下面你可以看到代码。假设Person
类具有所有成员的基本get / set函数。
Rules.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);
答案 0 :(得分:1)
Facts
对象本质上是一个hashmap。所以按照设计,你不能把两个事实放在同一把钥匙上。
我在你的例子中看到people
事实是一个数组。现在,如何在mvel表达式中处理数组是另一回事。说实话,我能给出的最佳答案是查看MVEL文档:https://github.com/imona/tutorial/wiki/MVEL-Guide#arrays
我想要实现的是在规则引擎的一次火灾中评估多个事实的规则。
我不确定这是否可以通过简单的规则实现。我想你可以:
fire
希望这有帮助。
答案 1 :(得分:1)
Fact
实际上只是一个Map
Map<String, Object> facts = new HashMap<>() // from source code
如果您需要添加多个事实,然后使用它们立即触发规则,则可以使用List
进行操作。可以创建一个List<Object>
并将此List
添加到Facts
。
规则类别:
@Rule(name = "Hello World rule", description = "Always say hello world")
public class HelloWorldRule {
@Condition
public boolean when() {
return true;
}
@Action
public void then(@Fact("facts") List<Object> arr) throws Exception {
for (Object i : arr) {
System.out.print(i + ", ");
}
}
}
启动器课程:
public class Launcher {
public static void main(String[] args) {
// create facts
Facts facts = new Facts();
List<Object> arr = new ArrayList<>();
arr.add("hello");
arr.add(5);
facts.put("facts", arr);
// create rules
Rules rules = new Rules();
rules.register(new HelloWorldRule());
// create a rules engine and fire rules on known facts
RulesEngine rulesEngine = new DefaultRulesEngine();
rulesEngine.fire(rules, facts);
}
}
请记住,如果您拥有所有相同类型的对象而不是Object
,例如本例中的Person
,这将非常有帮助。