Drools高级属性之global全局变量
定义
在我们编写drools的规则文件的时候,有些时候需要用到全局变量,那么这个该怎么实现呢?有哪些注意事项呢?
官方定义为
Global variables in DRL files typically provide data or services for the rules, such as application services used in rule consequences, and return data from rules, such as logs or values added in rule consequences. You set the global value in the working memory of the Drools engine through a KIE session configuration or REST operation, declare the global variable above the rules in the DRL file, and then use it in an action (then) part of the rule. For multiple global variables, use separate lines in the DRL file.
特点
全局变量的特点
- 使用global来定义全局变量,它可以为规则提供数据和服务。
- 全局变量并不会被写入到工作内存中,因此我们不可放到规则的约束条件中,即when的后面,除非这个全局变量是常量。
- 如果不同的包中存在相同标识符的常量,那么我们的常量必须是相同的类型,以便可以引用到相同的值。官网原文: If you declare global variables with the same identifier in multiple packages, then you must set all the packages with the same type so that they all reference the same global value.
- 尽量不要使用全局变量在规则之间传递参数,如果需要在规则之间传递参数,我们应该向工作内存中插入Fact对象。
示例
global关键字可以用来在规则文件中定义全局变量,它可以让应用程序中的对象在规则文件中都能够被访问。可以用来为规则文件提供数据或服务,从而贯穿整个规则文件的执行过程。该关键字的使用方式在下面的例子中会做介绍,我们编写一个规则文件,文件名为globalrule.drl,具体代码如下:
package rules.globals
import java.util.List;
import java.util.ArrayList;
import com.ppl.demo.entity.Account;
//此处定义一个全局计算数
global java.lang.Integer num;
//这里定义了一个普通的javaBean
global Account account;
//这里定义了一个简单的List集合
global List<String> list;
rule "rules-global-1"
when
then
//计算只在当前规则中有效
num=num+100;
System.out.println("这是规则rules-global-1的用户balance:"+account.getBalance());
list.