我正在使用drools引擎构建警报系统.当条件满足时,我们需要执行 Spring Framework对规则(RHS)的操作实例化的@Service方法.
什么方法可以让Spring Framework创建的@service实例被Drools规则的动作(RHS)使用?
我遵循了以下指示:
>使用表单导入功能(Rule1.drl).此解决方案不起作用,因为类在drools中实例化并且需要执行静态方法.
>使用全局会话变量(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;