【问题标题】:How to use a Spring Service in Drools rules?如何在 Drools 规则中使用 Spring Service?
【发布时间】:2017-09-06 20:34:08
【问题描述】:

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

如何让 Spring Framework 创建的 @service 实例 被 Drools 规则的操作 (RHS) 使用?

我已遵循以下指示:

  1. 使用表单导入函数 (Rule1.drl)。此解决方案不起作用,因为该类是在 drools 中实例化的,并且需要执行静态方法。
  2. 使用 全局会话 变量 (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

文件: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

文件: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);
    }

}

【问题讨论】:

    标签: spring dependency-injection drools kie mvel


    【解决方案1】:

    你可以使用kieRuntime的setGlobal函数为:

    kieRuntime.setGlobal("securityService", securityService);
    

    然后你可以在你的 drl 文件中声明/使用这个变量:

    global SecurityService securityService.
    

    PS:- KieRuntime 对象可以获取为:KieRuntime kieRuntime = (KieRuntime) kieSssion;

    【讨论】:

    • 或者你可以只做 kieSssion.setGlobal("securityService", securityService);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2023-03-11
    相关资源
    最近更新 更多