gpt4 book ai didi

spring - 如何在 Drools 规则中使用 Spring 服务?

转载 作者:行者123 更新时间:2023-12-02 09:04:22 24 4
gpt4 key购买 nike

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

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

我已遵循以下指示:

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

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

}

最佳答案

您可以使用 kieRuntime 的 setGlobal 函数:

kieRuntime.setGlobal("securityService", securityService);

然后您可以在 drl 文件中声明/使用此变量:

global SecurityService securityService.

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

关于spring - 如何在 Drools 规则中使用 Spring 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43346204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com