Drools-决策表
1、决策表
Drools除了支持drl形式的文件外还支持xls格式的文件(即Excel文件)。这种xls格式的文件通常称为决策表(decision table)。
决策表(decision table)是一个“精确而紧凑的”表示条件逻辑的方式,非常适合商业级别的规则。决策表与现有的drl文件可以无缝替换。Drools提供了相应的API可以将xls文件编译为drl格式的字符串
一个决策表的例子如下:
决策表的语法:
在决策表中还经常使用到占位符,语法为$后面加数字,用于替换每条规则中设置的具体值。
上面的决策表例子转换为drl格式的规则文件内容如下:
package rules; ? import com.itheima.drools.entity.PersonInfoEntity; import java.util.List; global java.util.List listRules; ? rule "personCheck_10" salience 65535 agenda-group "sign" when $person : PersonInfoEntity(sex != "男") then listRules.add("性别不对"); end ? rule "personCheck_11" salience 65534 agenda-group "sign" when $person : PersonInfoEntity(age < 22 || age > 25) then listRules.add("年龄不合适"); end ? rule "personCheck_12" salience 65533 agenda-group "sign" when $person : PersonInfoEntity(salary < 10000) then listRules.add("工资太低了"); end
要进行决策表相关操作,需要导入如下maven坐标:
org.drools drools-decisiontables 7.10.0.Final
通过下图可以发现,由于maven的依赖传递特性在导入drools-decisiontables坐标后,drools-core和drools-compiler等坐标也被传递了过来
Drools提供的将xls文件编译为drl格式字符串的API如下:
String realPath = "C:\\testRule.xls";//指定决策表xls文件的磁盘路径 File file = new File(realPath); InputStream is = new FileInputStream(file); SpreadsheetCompiler compiler = new SpreadsheetCompiler(); String drl = compiler.compile(is, InputType.XLS);
Drools还提供了基于drl格式字符串创建KieSession的API:
KieHelper kieHelper = new KieHelper(); kieHelper.addContent(drl, ResourceType.DRL); KieSession session = kieHelper.build().newKieSession();
2、基于决策表的入门案例
2.1、创建maven工程drools_decisiontable_demo并配置pom.xml文件
org.drools drools-decisiontables 7.10.0.Final junit junit 4.12
2.2、创建实体类PersonInfoEntity
package com.itheima.drools.entity; ? public class PersonInfoEntity { private String sex; private int age; private double salary; ? public String getSex() { return sex; } ? public void setSex(String sex) { this.sex = sex; } ? public int getAge() { return age; } ? public void setAge(int age) { this.age = age; } ? public double getSalary() { return salary; } ? public void setSalary(double salary) { this.salary = salary; } }
2.3、创建xls规则文件
2.4、创建单元测试
@Test public void test1() throws Exception{ String realPath = "d:\\testRule.xls";//指定决策表xls文件的磁盘路径 File file = new File(realPath); InputStream is = new FileInputStream(file); SpreadsheetCompiler compiler = new SpreadsheetCompiler(); String drl = compiler.compile(is, InputType.XLS); ? System.out.println(drl); KieHelper kieHelper = new KieHelper(); kieHelper.addContent(drl, ResourceType.DRL); KieSession session = kieHelper.build().newKieSession(); ? PersonInfoEntity personInfoEntity = new PersonInfoEntity(); personInfoEntity.setSex("男"); personInfoEntity.setAge(35); personInfoEntity.setSalary(1000); ? Listlist = new ArrayList (); session.setGlobal("listRules",list); ? session.insert(personInfoEntity); session.getAgenda().getAgendaGroup("sign").setFocus(); session.fireAllRules(); ? for (String s : list) { System.out.println(s); } session.dispose(); }