Drools中salience大的规则会先执行

规则文件
package test
import com.blackfish.demo.drools.Stu;

rule "rule1"
    salience 2
        when
            $stu:Stu(age > 30)
        then
            System.out.println("age>30岁的人: " + $stu.getName());
            $stu.setAmount(30000);
        end


rule "rule2"
salience 1
when
$stu:Stu(gender=="male", age> 25)
then System.out.println("性别为男,age>25的人: " + $stu.getName());
$stu.setAmount(8000);
end

rule "rule3"
salience 3
when
    $stu:Stu(getName() == "张三")
    then
    System.out.println("名字为:" + $stu.getName());
    $stu.setAmount(15000);
     end

     rule "rule4"
     salience 4
     when
         $stu:Stu(getName() == "张三", gender == "male")
         then
         System.out.println("性别为男,名字为:" + $stu.getName());
         $stu.setAmount(20000);
          end

测试case

public class Test {

    public static void main(String[] args) {
        KnowledgeBuilder kb = new KnowledgeBuilderFactory().newKnowledgeBuilder();
        kb.add(new ClassPathResource("test.drl"), ResourceType.DRL);
        Collection collection = kb.getKnowledgePackages();
        KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
        knowledgeBase.addKnowledgePackages(collection);
        StatefulKnowledgeSession statefulSession = knowledgeBase.newStatefulKnowledgeSession();

        List list = getStus();
        for(Stu stu : list) {
            statefulSession.insert(stu);
        }

        statefulSession.fireAllRules();
        statefulSession.dispose();
        System.out.println("End ...");
        for(Stu stu : list) {
            System.out.println(stu.toString());
        }
    }

    public static List getStus() {
        List stus = new ArrayList<>();
        stus.add(new Stu("张三", 16, "male"));
        stus.add(new Stu("huhu", 18, "male"));
        stus.add(new Stu("王五", 32, "male"));
        stus.add(new Stu("张红", 23, "female"));
        stus.add(new Stu("李四", 35, "male"));
        stus.add(new Stu("张小雅", 31, "female"));
        return stus;
    }
}

输出结果:

性别为男,名字为:张三  // salience 4

名字为:张三                   // salience 3
age>30岁的人: 张小雅   // salience 2
age>30岁的人: 李四       // salience 2
age>30岁的人: 王五        // salience 2
性别为男,age>25的人: 李四   // salience 1
性别为男,age>25的人: 王五    // salience 1
End ...
name : 张三, age : 16, gender :male, amount : 15000
name : huhu, age : 18, gender :male, amount : 0
name : 王五, age : 32, gender :male, amount : 8000
name : 张红, age : 23, gender :female, amount : 0
name : 李四, age : 35, gender :male, amount : 8000
name : 张小雅, age : 31, gender :female, amount : 30000

你可能感兴趣的:(Drool)