This blog post will guide you through integrating the Drools rule engine with your Spring Boot microservice. We’ll cover the necessary dependencies, configuration, and an example service to demonstrate its usage.

1. Project Setup and Dependencies

Start by creating a Spring Boot project using Spring Initializr or your preferred IDE. Next, add the following Drools dependencies to your pom.xml (Maven) or build.gradle (Gradle) file:

Maven:

<dependency>
    <groupId>org.kie</groupId>
    <artifactId>kie-spring</artifactId>
    <version>7.71.0.Final</version> 
</dependency>

Gradle:

implementation 'org.kie:kie-spring:7.71.0.Final'

2. Drools Configuration

Create a configuration class to set up the Drools environment. This class will define beans for KieFileSystem, KieContainer, KieSession, and optionally a KieBase.

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

@Configuration
public class DroolsConfig {

    private static final String RULES_PATH = "rules/";

    @Bean
    public KieFileSystem kieFileSystem() throws IOException {
        KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
        for (Resource file : getRuleFiles()) {
            kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_PATH + file.getFilename(), "UTF-8"));
        }
        return kieFileSystem;
    }

    private Resource[] getRuleFiles() throws IOException {
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        return resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "**/*.*");
    }

    @Bean
    public KieContainer kieContainer() throws IOException {
        final KieRepository kieRepository = getKieServices().getRepository();
        kieRepository.addKieModule(new KieModule() {
            public ReleaseId getReleaseId() {
                return kieRepository.getDefaultReleaseId();
            }
        });

        KieBuilder kieBuilder = getKieServices().newKieBuilder(kieFileSystem());
        kieBuilder.buildAll();
        return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
    }

    private KieServices getKieServices() {
        return KieServices.Factory.get();
    }

    @Bean
    public KieSession kieSession() throws IOException {
        return kieContainer().newKieSession();
    }

}

This configuration:

  • Defines the RULES_PATH where your Drools rule files (.drl) will be located.
  • Creates a KieFileSystem and loads all rule files from the specified path.
  • Builds a KieContainer to hold the compiled rules.
  • Creates a KieSession which is the primary interface for interacting with the Drools engine.

3. Create Drools Rule Files

Create a rules directory in your src/main/resources folder. Add your Drools rule files (.drl files) here. For example, discount.drl:

rule "Apply 10% discount for orders over $100"
when
    order : Order(totalPrice > 100)
then
    order.applyDiscount(0.1); 
end

4. Using the Drools Engine in a Service

Inject the KieSession bean into your service class and use it to fire rules against your domain objects.

import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @Autowired
    private KieSession kieSession;

    public Order applyRules(Order order) {
        kieSession.insert(order);
        kieSession.fireAllRules();
        return order;
    }
}

5. YML Configuration (Optional)

While not strictly required, you can configure Drools properties in your application.yml or application.properties file. This allows you to customize settings like logging levels and rule execution behavior.

drools:
  kbase:
    default:
      default-kiesession:
        type: stateless

This guide provides a basic framework for integrating Drools with your Spring Boot microservice. You can expand on this by exploring more advanced Drools features like decision tables, event processing, and complex event processing (CEP). Remember to adapt the rules and domain models to your specific business requirements.


Discover more from GhostProgrammer - Jeff Miller

Subscribe to get the latest posts sent to your email.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.