如何在Drools规则中使用Spring Service?

Hec*_*mez 6 spring dependency-injection drools mvel kie

我正在使用Drools引擎构建警报系统。当满足条件时,我们需要在规则(RHS)的操作上执行由Spring Framework 实例化@Service方法。

如何获得由Drools规则的动作(RHS)使用的Spring Framework创建的@service实例

我已遵循以下指示:

  1. 使用表单导入功能Rule1.drl)。该解决方案不起作用,因为该类是在drool中实例化的,并且需要执行静态方法。
  2. 使用全局Session变量(Rule2.drl)。此解决方案在“运行时”抛出异常,表明它不是同一类类型。

关于如何使用它的任何想法?

文件:Rule1.drl

package com.mycompany.alerts.Alert;

import function com.mycompany.alerts.service.SecurityService.notifyAlert;

rule "Activate Alert Type"
salience 9000
when
  $alert: Alert(type == "TYPE1") 
then
  System.out.println("Running action:" + drools.getRule().getName());
  $alert.setActive(Boolean.TRUE);
  notifyAlert($alert.getStatus(),$alert.getSmsNumber());    
  System.out.println("End action:" + drools.getRule().getName());
end
Run Code Online (Sandbox Code Playgroud)

文件:Rule2.drl

package com.mycompany.alerts.Alert;

global com.mycompany.alerts.service.SecurityService securityService;

rule "Activate Alert Type 2"
salience 9000
when
  $alert: Alert(type == "TYPE2") 
then
  System.out.println("Running action:" + drools.getRule().getName());
  $alert.setActive(Boolean.TRUE);
  securityService.notifyAlert($alert.getStatus(),$alert.getSmsNumber());    
  System.out.println("End action:" + drools.getRule().getName());
end
Run Code Online (Sandbox Code Playgroud)

文件:SecurityService.java

package com.mycompany.alerts.service;

import com.mycompany.alerts.service.UserRepository;

@Service
@Transactional
public class SecurityService {

    private final Logger log = LoggerFactory.getLogger(SecurityService.class);

    private final UserRepository userRepository;

    public SecurityService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void notifyAlert(String status, String sms) {
         System.out.println("Alert notify with:" + status + " sms:" + sms);
    }

}
Run Code Online (Sandbox Code Playgroud)

Abh*_*yal 6

您可以将kieRuntime的setGlobal函数用作:

kieRuntime.setGlobal("securityService", securityService);
Run Code Online (Sandbox Code Playgroud)

那么您可以在drl文件中声明/使用以下变量:

global SecurityService securityService.
Run Code Online (Sandbox Code Playgroud)

PS:-KieRuntime对象可以通过以下方式获得:KieRuntime kieRuntime =(KieRuntime)kieSssion;

  • 或者您可以只做kieSssion.setGlobal(“ securityService”,securityService); (2认同)