springboot整合drools
引入依赖
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-core</artifactId>
<version>7.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-compiler</artifactId>
<version>7.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-templates</artifactId>
<version>7.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>7.6.0.Final</version>
</dependency>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-spring</artifactId>
<version>7.6.0.Final</version>
</dependency>
编写配置类
@Configuration
public class DroolsConfig {
//drl文件的存放目录
private static final String RULES_PATH = "rules/";
private final KieServices kieServices = KieServices.Factory.get();
@SneakyThrows
@Bean
@ConditionalOnMissingBean
public KieFileSystem kieFileSystem(){
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
Resource[] files = resourcePatternResolver.getResources("classpath*:" + RULES_PATH + "*.*");
String path = null;
for (Resource file : files) {
path = RULES_PATH + file.getFilename();
kieFileSystem.write(ResourceFactory.newClassPathResource(path,"UTF-8"));
}
return kieFileSystem;
}
@Bean
public KieContainer kieContainer(){
KieRepository kieRepository = kieServices.getRepository();
kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem());
kieBuilder.buildAll();
return kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
}
@Bean
@ConditionalOnMissingBean
public KieBase kieBase(){
return kieContainer().getKieBase();
}
@Bean
@ConditionalOnMissingBean
public KModuleBeanFactoryPostProcessor kiePostProcessor(){
return new KModuleBeanFactoryPostProcessor();
}
}
编写规则
package rules;
import com.dqn.drools.droolsdemo.pojo.Order
rule "s1"
when
$order:Order(amout<100)
then
$order.setScore(0);
end
rule "s2"
when
$order:Order(amout>100&&amout<500)
then
$order.setScore(100);
end
rule "s3"
when
$order:Order(amout>500)
then
$order.setScore(300);
end
使用规则
@Service
public class RuleService {
@Autowired
private KieBase kieBase;
public Order executeRule(Order order){
KieSession kieSession = kieBase.newKieSession();
kieSession.insert(order);
kieSession.fireAllRules();
kieSession.dispose();
return order;
}
}