import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Applicant {
private String name;
private int age;
private boolean valid = true;
public Applicant(String name, int age) {
this.name = name;
this.age = age;
}
}
创建规则文件(放在类路径下,比如resources/rules/rules.drl)
//类似名称空间的作用,目前不用考虑
package rules;
dialect "mvel"
//此处引入对应实例
import com.drools.test.entity.*
rule "Is of valid age"
when
$a:Applicant(age < 18);
then
$a.setValid(false);
end
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Room {
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Fire {
private Room room;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Sprinkler {
private Room room;
private boolean on;
public Sprinkler(Room room) {
this.room = room;
}
}
public class Alarm {
}
创建规则文件
rule "When there is a fire turn on the sprinkle"
salience 1
when
Fire($room : room)
$sprinkler:Sprinkler($room == room, on == false);
then
modify($sprinkler){setOn(true)}
System.out.println("room 【" + $room.getName() + "】 is firing!!!");
System.out.println("Turn on the sprinkler from room 【" + $room.getName() + "】.");
end
rule "When the fire is gone trun off the srinkle"
when
$room:Room();
$sprinkler:Sprinkler($room == room, on == true);
not Fire($room == room);
then
modify($sprinkler){setOn(false)}
System.out.println("Room 【" + $room.getName() + "】 fire is gone.");
System.out.println("Turn off the sprinkler from room 【" + $room.getName() + "】.");
end
rule "Raise the alarm when have one or more fires"
//先报警,在开喷头
salience 2
when
exists Fire();
then
insert(new Alarm())
System.out.println("Raise the alarm.");
end
rule "Cancel the alarm when all the fires have gone"
when
not Fire();
$alarm:Alarm()
then
delete($alarm);
System.out.println("Cancel the alarm.");
end
rule "Status output when things are ok"
when
not Alarm();
not Sprinkler(on == true);
then
System.out.println("Everything is ok.");
end
测试用例
@Test
public void test02(){
KieServices kieServices = KieServices.Factory.get();
KieContainer kieClasspathContainer = kieServices.getKieClasspathContainer();
KieSession kieSession = kieClasspathContainer.newKieSession();
String[] roomNames = new String[]{"kitchen", "bedroom", "office", "living-room"};
List<Room> rooms = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Room room = new Room(roomNames[i]);
rooms.add(room);
Sprinkler sprinkler = new Sprinkler(room);
kieSession.insert(room);
kieSession.insert(sprinkler);
}
//一切ok
kieSession.fireAllRules();
FactHandle bedroomHandle = kieSession.insert(new Fire(rooms.get(1)));
//卧室发生火灾
kieSession.fireAllRules();
//扑灭卧室火灾
kieSession.delete(bedroomHandle);
kieSession.fireAllRules();
kieSession.dispose();
}