Drools 6.0 onwards a new approach is designed to create a Knowledge Base and a Knowledge Session compared to previous versions.
The below example will explain on how to create a Default KieSession
The Drools 6.0 project consists of a single meta data file META-INF/kmodule.xml. The file is located under the source folder as shown in below snapshot.
If the file is not located at the location
KieSession ksession = kc.newKieSession(); // will return null
By default, kc.newKieSession() returns the object of org.drools.core.impl.StatefulKnowledgeSessionImpl class.
Below are the files that are required to fire the rules using KieSession
kmodule.xml file - Since we are creating a default KieSession, no need to define any kbase
<?xml version="1.0" encoding="UTF-8"?> <kmodule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://jboss.org/kie/6.0.0/kmodule"> </kmodule>
DRL File
package com.sample import com.pojo.*; rule "Check Circuit Limit" when $stock : Stock() then $stock.setHaltTrading(true); System.out.println("Rule Fired using KIE Default Session"); end
Client File
package com.sample; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.internal.KnowledgeBase; import com.pojo.Stock; /** * This is a sample class to launch a rule. */ public class DroolsTest { public static final void main(String[] args) { try { KieServices ks = KieServices.Factory.get(); KieContainer kc = ks.getKieClasspathContainer(); KieSession ksession = kc.newKieSession(); System.out.println("KieSession - " +ksession); final Stock a = new Stock(); ksession.insert(a); ksession.fireAllRules(); ksession.dispose(); // Stateful rule session must always be disposed // when finished } catch (Throwable t) { t.printStackTrace(); } } }
Output:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. KieSession - org.drools.core.impl.StatefulKnowledgeSessionImpl@cab854 Rule Fired using KIE Default Session
No comments:
Post a Comment