ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Drools基础语法(4/6)

2021-11-17 12:00:45  阅读:243  来源: 互联网

标签:Drools Student 10 age 基础 rule 语法 student 规则


1、规则文件构成

在使用Drools时非常重要的一个工作就是编写规则文件,通常规则文件的后缀为.drl。

drl是Drools Rule Language的缩写。在规则文件中编写具体的规则内容。

一套完整的规则文件内容构成如下:

Drools支持的规则文件,除了drl形式,还有Excel文件类型的。

2、规则体语法结构

规则体是规则文件内容中的重要组成部分,是进行业务规则判断、处理业务结果的部分。

规则体语法结构如下:

rule "ruleName"
    attributes
    when
        LHS
    then
        RHS
end
rule:关键字,表示规则开始,参数为规则的唯一名称。

attributes:规则属性,是rule与when之间的参数,为可选项。

when:关键字,后面跟规则的条件部分。

LHS(Left Hand Side):是规则的条件部分的通用名称。它由零个或多个条件元素组成。如果LHS为空,则它将被视为始终为true的条件元素。

then:关键字,后面跟规则的结果部分。

RHS(Right Hand Side):是规则的后果或行动部分的通用名称。

end:关键字,表示一个规则结束。

3、注释

在drl形式的规则文件中使用注释和Java类中使用注释一致,分为单行注释和多行注释。

单行注释用"//"进行标记,多行注释以"/*"开始,以"*/"结束。如下示例:

//规则rule1的注释,这是一个单行注释
rule "rule1"
    when
    then
        System.out.println("rule1触发");
end
​
/*
规则rule2的注释,
这是一个多行注释
*/
rule "rule2"
    when
    then
        System.out.println("rule2触发");
end

4、模式匹配

前面我们已经知道了Drools中的匹配器可以将Rule Base中的所有规则与Working Memory中的Fact对象进行模式匹配,那么我们就需要在规则体的LHS部分定义规则并进行模式匹配。LHS部分由一个或者多个条件组成,条件又称为pattern。

pattern的语法结构为:绑定变量名:Object(Field约束)

其中绑定变量名可以省略,通常绑定变量名的命名一般建议以$开始。如果定义了绑定变量名,就可以在规则体的RHS部分使用此绑定变量名来操作相应的Fact对象。Field约束部分是需要返回true或者false的0个或多个表达式。

例如我们的入门案例中:
//规则二:所购图书总价在100到200元的优惠20元
rule "book_discount_2"
    when
        //Order为类型约束,originalPrice为属性约束
        $order:Order(originalPrice < 200 && originalPrice >= 100)
    then
        $order.setRealPrice($order.getOriginalPrice() - 20);
        System.out.println("成功匹配到规则二:所购图书总价在100到200元的优惠20元");
end

通过上面的例子我们可以知道,匹配的条件为:

  • 工作内存中必须存在Order这种类型的Fact对象-----类型约束
  • Fact对象的originalPrice属性值必须小于200------属性约束
  • Fact对象的originalPrice属性值必须大于等于100------属性约束
  • 以上条件必须同时满足当前规则才有可能被激活。

绑定变量既可以用在对象上,也可以用在对象的属性上。例如上面的例子可以改为:

//规则二:所购图书总价在100到200元的优惠20元
rule "book_discount_2"
    when
        $order:Order($op:originalPrice < 200 && originalPrice >= 100)
    then
        System.out.println("$op=" + $op);
        $order.setRealPrice($order.getOriginalPrice() - 20);
        System.out.println("成功匹配到规则二:所购图书总价在100到200元的优惠20元");
end

LHS部分还可以定义多个pattern,多个pattern之间可以使用and或者or进行连接,也可以不写,默认连接为and。

//规则二:所购图书总价在100到200元的优惠20元
rule "book_discount_2"
    when
        $order:Order($op:originalPrice < 200 && originalPrice >= 100) and
        $customer:Customer(age > 20 && gender=='male')
    then
        System.out.println("$op=" + $op);
        $order.setRealPrice($order.getOriginalPrice() - 20);
        System.out.println("成功匹配到规则二:所购图书总价在100到200元的优惠20元");
end

5、比较操作符

Drools提供的比较操作符,如下表:

5.1 语法

  • contains | not contains语法结构 Object(Field[Collection/Array] contains value) Object(Field[Collection/Array] not contains value)
  • memberOf | not memberOf语法结构 Object(field memberOf value[Collection/Array]) Object(field not memberOf value[Collection/Array])
  • matches | not matches语法结构 Object(field matches "正则表达式") Object(field not matches "正则表达式")

5.2 操作步骤

第一步:创建实体类,用于测试比较操作符

package com.itheima.drools.entity;
 
import java.util.List;
 
/**
 * 用于测试比较操作符
 */
public class ComparisonOperatorEntity
{
    private String names;
    private List<String> list;
 
    public String getNames()
    {
        return names;
    }
 
    public void setNames(String names)
    {
        this.names = names;
    }
 
    public List<String> getList()
    {
        return list;
    }
 
    public void setList(List<String> list)
    {
        this.list = list;
    }
}

第二步:在/resources/rules下创建规则文件comparisonOperator.drl

package comparisonOperator
import com.itheima.drools.entity.ComparisonOperatorEntity
 
/*
    当前规则文件用于测试Drools提供的比较操作符
*/
 
//测试比较操作符contains
rule "rule_comparision"
    when
        ComparisonOperatorEntity(names contains "张三") and
        ComparisonOperatorEntity(list contains names)
    then
        System.out.println("规则:rule_comparison_contains触发了、、、");
end
 
//测试比较操作符not contains
rule "rule_comparision2"
    when
        ComparisonOperatorEntity(names not contains "张三") and
        ComparisonOperatorEntity(list not contains names)
    then
        System.out.println("规则:rule_comparison_contains触发了、、、");
end
 
//测试比较操作符memberOf
rule "rule_comparison_memberOf"
    when
        ComparisonOperatorEntity(names memberOf list)
    then
        System.out.println("规则:rule_comparison_memberOf触发了、、、、");
end
 
//测试比较操作符not memberOf
rule "rule_comparison_not memberOf"
    when
        ComparisonOperatorEntity(names not memberOf list)
    then
        System.out.println("规则:rule_comparison_not memberOf触发了、、、、");
end
 
//测试比较操作符matches
rule "rule_comparison_matches"
    when
        ComparisonOperatorEntity(names matches "郭.*");
    then
        System.out.println("规则:rule_comparison_matches触发了、、、、");
end
 
//测试比较操作符matches
rule "rule_comparison_not matches"
    when
        ComparisonOperatorEntity(names not matches "郭.*");
    then
        System.out.println("规则:rule_comparison_not matches触发了、、、、");
end

第三步:编写单元测试

    package com.itheima.test;
 
    import com.itheima.drools.entity.ComparisonOperatorEntity;
    import com.itheima.drools.entity.Order;
    import org.junit.Test;
    import org.kie.api.KieServices;
    import org.kie.api.runtime.KieContainer;
    import org.kie.api.runtime.KieSession;
 
    import java.util.ArrayList;
    import java.util.List;
 
    public class DroolsTest
    {
        @Test
        public void test1()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            Order order = new Order();
            order.setOriginalPrice(500d);
 
            //将order对象插入到规则内存中
            session.insert(order);
 
            //激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
            int count = session.fireAllRules();
            System.out.println(count);
 
            //关闭会话
            session.dispose();
 
            System.out.println("优惠后的价格: " + order.getRealPrice());
        }
 
        @Test
        public void test2()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
            fact.setNames("李四");
            List<String> list = new ArrayList<String>();
            list.add("张三");
            list.add("李四");
 
            fact.setList(list);
 
            session.insert(fact);
 
            //激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
            session.fireAllRules();
 
            //关闭会话
            session.dispose();
 
        }
    }
 

6、执行指定规则

AgendaFilter接口的实现类

//测试制定规则
        @Test
        public void test3()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
            fact.setNames("李四");
            List<String> list = new ArrayList<String>();
            list.add("张三");
            list.add("李四");
 
            fact.setList(list);
 
            session.insert(fact);
 
            //激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
            //过滤器【使用框架提供的规则过滤器执行指定规则】
            session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_comparison_not matches"));
 
            //关闭会话
            session.dispose();
 
        }

7、关键字

Drools的关键字分为:硬关键字(Hard keywords)和软关键字(Soft keywords)。

硬关键字是我们在规则文件中定义包名或者规则名时明确不能使用的,否则程序会报错。软关键字虽然可以使用,但是不建议使用。

硬关键字包括:true false null

软关键字包括:lock-on-active date-effective date-expires no-loop auto-focus activation-group agenda-group ruleflow-group entry-point duration package import dialect salience enabled attributes rule extend when then template query declare function global eval not in or and exists forall accumulate collect from action reverse result end over init

8、Drools内置方法

规则文件的RHS部分的主要作用是通过插入,删除或修改工作内存中的Fact数据,来达到控制规则引擎执行的目的。Drools提供了一些方法可以用来操作工作内存中的数据,操作完成后规则引擎会重新进行相关规则的匹配,原来没有匹配成功的规则在我们修改数据完成后有可能就会匹配成功了。

创建如下实体类:

package com.itheima.drools.entity;
 
/**
 * 学生实体
 */
public class Student {
    private int id;
    private String name;
    private int age;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}

8.1 update方法 

update方法的作用是更新工作内存中的数据,并让相关的规则重新匹配。

第一步:编写规则文件/resources/rules/student.drl,文件内容如下

//当前规则文件用于测试Drools内置方法
package student
import com.itheima.drools.entity.Student
 
//当前规则用于测试update内置方法
rule "要求Student的age小于10岁"
    when
        $student:Student(age < 10)
    then
        $student.setAge(15);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age小于10岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于10岁并且小于20岁"
    when
        $student:Student(age >= 10 && age < 20)
    then
        $student.setAge(25);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age大于10岁并且小于20岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于20岁"
    when
        $student:Student(age >= 20)
    then
        System.out.println("规则:要求Student的age大于20岁触发了、、、、");
end

第二步:编写单元测试

        //测试内置方法
        @Test
        public void test4()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            Student student = new Student();
            student.setAge(5);
 
            session.insert(student);
 
            session.fireAllRules();
 
            session.dispose();
 
        }

8.2 insert方法

insert方法的作用是向工作内存中插入数据,并让相关的规则重新匹配。

第一步:修改student.drl文件内容如下

//当前规则文件用于测试Drools内置方法
package student
import com.itheima.drools.entity.Student
 
//当前规则用于测试insert内置方法
rule "要求Student的age等于10岁"
    when
        $student:Student(age == 10)
    then
        Student student =  new Student();
        student.setAge(5);
        insert(student);  //insert方法作用是向工作内存中插入Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age等于10岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age小于10岁"
    when
        $student:Student(age < 10)
    then
        $student.setAge(15);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age小于10岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于10岁并且小于20岁"
    when
        $student:Student(age > 10 && age < 20)
    then
        $student.setAge(25);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age大于10岁并且小于20岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于20岁"
    when
        $student:Student(age > 20)
    then
        System.out.println("规则:要求Student的age大于20岁触发了、、、、");
end

第二步:编写单元测试

        //测试内置方法--insert
        @Test
        public void test5()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            Student student = new Student();
            student.setAge(10);
 
            session.insert(student);
 
            session.fireAllRules();
 
            session.dispose();
 
        }

通过控制台输出可以发现,四个规则都触发了,这是因为首先进行规则匹配时只有第一个规则可以匹配成功,但是在第一个规则中向工作内存中插入了一个数据导致重新进行规则匹配,此时第二个规则可以匹配成功。在第二个规则中进行了数据修改导致第三个规则也可以匹配成功,以此类推最终四个规则都匹配成功并执行了。

8.3 retract方法

retract方法的作用是删除工作内存中的数据,并让相关的规则重新匹配。

第一步:修改student.drl文件内容如下

//当前规则文件用于测试Drools内置方法
package student
import com.itheima.drools.entity.Student
 
//当前规则用于测试retract内置方法
rule "要求Student的age等于10岁时删除数据`"
    when
        $student:Student(age == 10)
    then
        retract($student);//retract方法的作用是删除工作内存中的数据,并让相关的规则重新匹配
        System.out.println("规则rule_student_age等于10岁时删除数据触发");
 
end
 
//当前规则用于测试insert内置方法
rule "要求Student的age等于10岁"
    when
        $student:Student(age == 10)
    then
        Student student =  new Student();
        student.setAge(5);
        insert(student);  //insert方法作用是向工作内存中插入Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age等于10岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age小于10岁"
    when
        $student:Student(age < 10)
    then
        $student.setAge(15);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age小于10岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于10岁并且小于20岁"
    when
        $student:Student(age > 10 && age < 20)
    then
        $student.setAge(25);
        update($student);  //update方法用于更新Fact对象,会导致相关规则重新匹配
        System.out.println("规则:要求Student的age大于10岁并且小于20岁触发了、、、、");
end
 
//当前规则用于测试update内置方法
rule "要求Student的age大于20岁"
    when
        $student:Student(age > 20)
    then
        System.out.println("规则:要求Student的age大于20岁触发了、、、、");
end

第二步:编写单元测试

        //测试内置方法--insert
        @Test
        public void test5()
        {
            KieServices kieServices = KieServices.Factory.get();
            //获得Kie容器对象
            //默认自动加载 META-INF/kmodule.xml
            //从KieServices中获得KieContainer实例,其会加载kmodule.xml文件并load规则文件
            KieContainer kieContainer = kieServices.getKieClasspathContainer();
            //从Kie容器对象中获取会话对象
            KieSession session = kieContainer.newKieSession();
 
            //Fact对象,事实对象
            Student student = new Student();
            student.setAge(10);
 
            session.insert(student);
 
            session.fireAllRules();
 
            session.dispose();
 
        }

标签:Drools,Student,10,age,基础,rule,语法,student,规则
来源: https://www.cnblogs.com/gentlescholar/p/15566556.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有