文章字数:230,阅读全文大约需要1分钟
Drools是一款java规则引擎,其目的是为了将if..else这样的业务逻辑与业务代码分离。
添加依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <dependencies> <dependency> <groupId>org.kie</groupId> <artifactId>kie-api</artifactId> <version>6.5.0.Final</version> </dependency> <dependency> <groupId>org.drools</groupId> <artifactId>drools-compiler</artifactId> <version>6.5.0.Final</version> <scope>runtime</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
|
配置文件
新建/src/resources/META-INF/kmodule.xml
1 2 3 4 5 6 7 8
| <?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> <!-- name任意 packages为resources下drl所在的包 --> <kbase name="rules" packages="rules"> <!-- ksession名字任意 --> <ksession name="myAgeSession"/> </kbase> </kmodule>
|
drl文件
1 2 3 4 5 6 7 8 9 10 11 12
| //package rules //包名,不必和物理路径一样 import com.learndrools.learndrools.User //导入Bean的完整路径,也可导入静态方法 dialect "mvel" rule "age" //唯一规则名,可多次执行 //salience 1 //优先级越大越高,如果不设置随机顺序 //no-loop true //规则是否只执行一次,默认false,多次执行 //lock-on-active true //避免因某些Fact对象被修改而使已经执行过的规则再次被激活执行。 when $user: User(age<15 || age>60) // 声明变量:Bean(规则),变量通常$开头 then System.out.println($user.getName()+"年龄不符合"); end
|
执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package com.learndrools.learndrools;
import org.junit.Test; import org.junit.runner.RunWith; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class LearndroolsApplicationTests {
@Test public void contextLoads() { }
private static KieContainer container = null; private KieSession statefulKieSession = null;
@Test public void test(){ KieServices kieServices = KieServices.Factory.get(); container = kieServices.getKieClasspathContainer(); statefulKieSession = container.newKieSession("myAgeSession"); User user = new User("zhang san",90); statefulKieSession.insert(user); statefulKieSession.fireAllRules(); statefulKieSession.dispose(); } }
|