Drools Named KieSession example - Java @ Desk

Friday, June 26, 2015

Drools Named KieSession example

Drools Named KieSession example

Drools 6.0 onwards a new approach is designed to create a Knowledge Base and a Knowledge Session compared to previous versions.

In our last post, we learned Drools Default KieSession example The below example will explain on how to create a Named 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 = 


// will return null

If the named session is not defined in kmodule.xml
KieSession ksession = 
// will return null

By default, kc.newKieSession("namedKieSession") returns the object of org.drools.core.impl.StatefulKnowledgeSessionImpl class.

Below are the files that are required to fire the rules using KieSession

<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    <kbase name="DroolsTestKB" packages="org.drools.test">
        <ksession name="namedKieSession"/>


DRL File
package com.sample
import com.pojo.*;
rule "Check Circuit Limit"
 $stock : Stock()
 System.out.println("Rule Fired using KIE Default Session");

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("namedKieSession");
   System.out.println("KieSession - " +ksession);

   final Stock a = new Stock();



   ksession.dispose(); // Stateful rule session must always be disposed
   // when finished
  } catch (Throwable t) {


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 Named Session

No comments:

Post a Comment