第 86 章 决策引擎查询和实时查询
您可以将查询与决策引擎配合使用,以检索基于规则中事实模式的事实集。模式可能也使用可选参数。
要将查询与决策引擎一起使用,您可以在 DRL 文件中添加查询定义,然后获取应用程序代码的匹配结果。虽然查询迭代结果集合,但您可以使用绑定到查询的任何标识符来访问对应的 fact 或 fact 字段,方法是调用带有绑定变量名称的 get() 方法作为其参数。如果绑定引用了事实对象,您可以通过调用 getFactHandle() 和变量名称作为 参数来检索事实句柄。
DRL 文件中的查询定义示例
query "people under the age of 21"
$person : Person( age < 21 )
end
获取和迭代查询结果的应用程序代码示例
QueryResults results = ksession.getQueryResults( "people under the age of 21" );
System.out.println( "we have " + results.size() + " people under the age of 21" );
System.out.println( "These people are under the age of 21:" );
for ( QueryResultsRow row : results ) {
Person person = ( Person ) row.get( "person" );
System.out.println( person.getName() + "\n" );
}
监控时间发生变化时,通过迭代返回的集合调用查询和处理结果会比较困难。为了减少对持续查询的难度,红帽决策管理器提供了 实时查询,它使用附加的监听程序更改事件,而不是返回可迭代结果集。通过创建视图并为此视图的内容发布更改事件,以保持实时查询保持打开状态。
要激活实时查询,请使用参数启动查询,并在生成的视图中监控更改。您可以使用 dispose() 方法终止查询并停止此重试场景。
DRL 文件中的查询定义示例
query colors(String $color1, String $color2)
TShirt(mainColor = $color1, secondColor = $color2, $price: manufactureCost)
end
带有事件监听程序和实时查询的应用程序代码示例
final List updated = new ArrayList();
final List removed = new ArrayList();
final List added = new ArrayList();
ViewChangedEventListener listener = new ViewChangedEventListener() {
public void rowUpdated(Row row) {
updated.add( row.get( "$price" ) );
}
public void rowRemoved(Row row) {
removed.add( row.get( "$price" ) );
}
public void rowAdded(Row row) {
added.add( row.get( "$price" ) );
}
};
// Open the live query:
LiveQuery query = ksession.openLiveQuery( "colors",
new Object[] { "red", "blue" },
listener );
...
...
// Terminate the live query:
query.dispose()