如何在Drools中编写有状态和基于时间的规则?

时间:2019-01-23 23:56:06

标签: java drools

我正在尝试使用Drools编写基于规则的引擎。规则是这样的:

规则“警报”:如果状态为“警报”,则立即发送通知。

规则“警告”:如果状态为“警告”,则将设备ID保存在内存中并等待5分钟。如果在5分钟内收到另一条具有相同设备ID和状态“已解决”的消息,请取消此规则。否则,将状态升级为“警报”并触发规则“警报”。

“已解决”规则:如果状态为“已解决”并且设备ID已在内存中,则清除该设备ID的“警告”,即从内存中删除设备ID。

规则警报很简单并且正在运行。但是警告和解决规则显然不适用于我的代码。如何在Drools中编写这样的规则?

这是我到目前为止编写的代码:

DroolsTest.java

package com.sample;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;

public class DroolsTest {

    public static final void main(String[] args) {
        try {
            // load up the knowledge base
            KnowledgeBase kbase = readKnowledgeBase();
            StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
            KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
            // go !
            MachineMessage[] messages = new MachineMessage[4]; 
            messages[0] = new MachineMessage("1", "Warning");
            messages[1] = new MachineMessage("2", "Alarm");
            messages[2] = new MachineMessage("3", "Alarm");
            messages[3] = new MachineMessage("1", "Resolved");

            for(int i = 0; i < messages.length; i++)
            {
                ksession.insert(messages[i]);
                ksession.fireAllRules();
                Thread.sleep(9000);
            }
            logger.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private static KnowledgeBase readKnowledgeBase() throws Exception {
        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        kbuilder.add(ResourceFactory.newClassPathResource("Sample.drl"), ResourceType.DRL);
        KnowledgeBuilderErrors errors = kbuilder.getErrors();
        if (errors.size() > 0) {
            for (KnowledgeBuilderError error: errors) {
                System.err.println(error);
            }
            throw new IllegalArgumentException("Could not parse knowledge.");
        }
        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
        kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
        return kbase;
    }

    public static class MachineMessage {

        private String deviceID;
        private String status;

        public MachineMessage() { }
        public MachineMessage(String deviceID, String status) {
            this.deviceID = deviceID;
            this.status = status;           
        }

        public String getDeviceID() {
            return this.deviceID;
        }

        public void setDeviceID(String deviceID) {
            this.deviceID = deviceID;
        }

        public String getStatus() {
            return this.status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }
}

Sample.drl

package com.sample

import com.sample.DroolsTest.MachineMessage;

rule "Alarm"
when
    m : MachineMessage( status == "Alarm", myDeviceID : deviceID )
then
    System.out.println("Send notification to technician, device in Alarm state. Device ID: " +  myDeviceID );
end

rule "Warning"
when
    m : MachineMessage( status == "Warning", myDeviceID : deviceID )
then
    System.out.println("Wait for 5 minutes, device in Warning state. Device ID: " + myDeviceID);        
    // if we get Machine Message with the same device ID and Resolved status in 5 minutes then 
    // we'll not trigger the following line
    m.setStatus("Alarm");
    update(m);
end

rule "Resolved"
when
    m : MachineMessage( status == "Resolved", myDeviceID : deviceID )
then
    System.out.println("Device has resolved its warning state. Device ID: " + myDeviceID);

end

我得到的实际输出是这样:

    Wait for 5 minutes, device in Warning state. Device ID: 1
    Send notification to technician, device in Alarm state. Device ID: 1
    Send notification to technician, device in Alarm state. Device ID: 2
    Send notification to technician, device in Alarm state. Device ID: 3
    Device has resolved its warning state. Device ID: 1

我想要的是:

    Wait for 5 minutes, device in Warning state. Device ID: 1
    Send notification to technician, device in Alarm state. Device ID: 2
    Send notification to technician, device in Alarm state. Device ID: 3
    Device has resolved its warning state. Device ID: 1

1 个答案:

答案 0 :(得分:0)

根据Drools documentation on CEP事件应该是不可变的:

  

最佳做法是,允许应用程序填充未填充的事件属性(以用推断的数据丰富事件),但绝不应更改已填充的属性。

因此很明显,规则“警告”已经通过OP提出的方式(改变“状态”字段)已经不符合CEP的第一个要求。

可能的建议是:

rule "Warning"
when
    m : MachineMessage( status == "Warning", myDeviceID : deviceID )
    not( MachineMessage( status == "Resolved", deviceID == m.deviceID, this after[0s, 30s] m) )
then
    System.out.println("I waited for 5 minutes, device in Warning state not followed by Resolved. Device ID: " + myDeviceID);        
    insert(new MachineMessage(m.deviceID, "Alarm"));
end

不会更改现有事件的任何价位字段,并且实际上会进行CEP知识推断,以尝试匹配OP描述的业务需求。

通常the CEP example in the Drools manual of sprinkler/fire alarms似乎符合OP所述的业务要求。