How to create a Drools Knowledge Base as Singleton - Java @ Desk

Thursday, July 10, 2014

How to create a Drools Knowledge Base as Singleton

How to create a Drools Knowledge Base as Singleton

Running a drools application in a web application would be similar to the one while running in a standalone java application.

It is advisable to create a Knowledge Base within an application as a Singleton class. For each client request, a new StatefulKnowledgeSession or StatelessKnowledgeSession is created based on the requirement.

Advantages of creating a KnowledgeBase as Singleton class :

1) There will be only 1 instance of KnowledgeBase across the whole application
2) Different requests will use the same instance to create knowledge session
3) Loading of all the DRL files happens at once saving a lot of time
4) KnowledgeBase initialization can be eagerly loaded. Thus as soon as the application starts in the server, KnowledgeBase is created. So on first client request for rule firing, processing time will be saved as the KnowledgeBase is already in place, just to create a Session out of it.

Sample singleton class for KnowledgeBase

Spring Bean Entry configuration : In a spring configuration XML, following entry helps in eager initialization of the KnowledgeBase.

<bean id="knowledgeBase" class="com.sample.DroolsSingletonKnowledgeBase" init-method="getKnowledgeBase()">


package com.sample;

import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;

public class DroolsSingletonKnowledgeBase {

 private static KnowledgeBase knowledgeBase;
 
 private DroolsSingletonKnowledgeBase() {
  
 }
 
 public static KnowledgeBase getKnowledgeBase() {
  if(knowledgeBase == null) {
   knowledgeBase = createKnowledgeBase();
  }
  return knowledgeBase;
 }
 
 private static KnowledgeBase createKnowledgeBase() {
  KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
  
  // Add Drools Files
  // knowledgeBuilder.add(arg0, arg1);
  
  KnowledgeBuilderErrors knowledgeBuilderErrors = knowledgeBuilder.getErrors();
  if(knowledgeBuilderErrors.size() > 0) {
   for(KnowledgeBuilderError knowledgeBuilderError : knowledgeBuilderErrors) {
    System.out.println("Error : " + knowledgeBuilderError);
   }
   throw new RuntimeException("Could not parse Knowledge Base");
  }
  
  KnowledgeBase knowledgeBase = knowledgeBuilder.newKnowledgeBase();
  knowledgeBase.addKnowledgePackages(knowledgeBuilder.getKnowledgePackages());
  return knowledgeBase;
 }
}






No comments:

Post a Comment