drools 学习笔记

1、基本的使用

1.1、无状态回话

无状态回话,不使用推理,类似于函数的调用过程。传入参数->然后得到结果

主要有一下用途(不限于此)

  • 验证规则(Validation)
  • 计算数值(Calculation)
  • 路由和过滤(Routing and Filtering)
    • Filter incoming messages, such as emails, into folders.
    • Send incoming messages to a destination.

下面是一个简单的无状态回话的例子:

public class Applicant {
    private String name;
    private int age;
    private boolean valid;
    // getter and setter methods here
}

规则如下

package com.company.license
rule "Is of valid age"
when
    $a : Applicant( age < 18 )
then
    $a.setValid( false );
end

当Applicant实例插入到引擎中时,将根据规则的约束进行评估,在这种情况下,这只是一个规则的两个约束条件。第一个约束为 Applicant 类型约束,第二个为年龄(字段)大于18 也就是说满足这两个条件的实例才会匹配这个规则。 0-N个字段的约束被称为 模式 $a 是一个变量 绑定到被匹配的实例 他的属性可以更新(名称可以是任意的,建议用$开头 和 字段变量区别)

The process of matching patterns against the inserted data is, not surprisingly, often referred to as pattern matching.

插入的数据和这些模式的匹配过程叫做 模式匹配

1.2、有状态的回话

Stateful Sessions are long lived and allow iterative changes over time 有状态会话长期存在,并允许随着时间的推移进行迭代更改。(基番)

应用场景

  • Monitoring(监控) Stock market monitoring and analysis for semiautomatic buying.
  • Diagnostics(诊断) Fault finding, medical diagnostics
  • Logistics Parcel tracking and delivery provisioning
  • Compliance Validation of legality for market trades.

有状态session和无状态session不同的是 前者必须明确调用dispose()方法注销对象,(因为KieBase在创建状态知识会话时会包含它们的引用)

栗子:对房间火灾状况的监控 用四个类来表示 假设有一个房子每个房间(room)都有一个洒水器(Sprinkler),一个报警装置(Alarm) ;模拟出现火情(Fire)

public class Room {
    private String name
    // getter and setter methods here
}
public class Sprinkler {
    private Room room;
    private boolean on;
    // getter and setter methods here
}
public class Fire {
    private Room room;
    // getter and setter methods here
}
public class Alarm {
}

房子有许多房间,因此规则必须表达物体之间的关系,例如在某个房间内的喷洒器。 这最好通过使用绑定变量作为模式中的约束来完成。(基番)

rule "When there is a fire turn on the sprinkler"
when
    Fire($room : room)
    $sprinkler : Sprinkler( room == $room, on == false )
then
    modify( $sprinkler ) { setOn( true ) };
    System.out.println( "Turn on the sprinkler for room " + $room.getName() );
end

与无状态不同的是前面采用java 语法来修改字段,这里使用 modify 修改,他会通知规则引擎获取更改的动作,再次出发该动作,这个过程成为 推理 可以通过 sequential mode 关闭推理

下面模拟灭火后的情况

rule "When the fire is gone turn off the sprinkler"
when
    $room : Room( )
    $sprinkler : Sprinkler( room == $room, on == true )
    not Fire( room == $room )
then
    modify( $sprinkler ) { setOn( false ) };
    System.out.println( "Turn off the sprinkler for room " + $room.getName() );
end

转载于:https://my.oschina.net/sandbela/blog/909425

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值