Drools通过Java API定时执行规则

时间:2019-02-01 08:41:55

标签: java drools kie kie-server

我想创建一个基于时间的规则,每5分钟触发一次,Drools文档指出:

  

相反,默认情况下,当Drools引擎在被动模式下运行(即:使用fireAllRules代替fireUntilHalt)时,除非再次调用fireAllRules,否则不会触发定时规则的结果。但是,可以通过使用TimedRuleExecutionOption配置KieSession来更改此默认行为,如以下示例所示

KieSessionConfiguration ksconf = KieServices.Factory.get().newKieSessionConfiguration();
ksconf.setOption( TimedRuleExecutionOption.YES );
KSession ksession = kbase.newKieSession(ksconf, null);

但是,我没有直接访问KieSession对象,因为我正在使用Java REST API将请求发送到部署在KieExecution Server上的Drools项目,就像这样(示例直接取自Drools文档):

public class MyConfigurationObject {

  private static final String URL = "http://localhost:8080/kie-server/services/rest/server";
  private static final String USER = "baAdmin";
  private static final String PASSWORD = "password@1";

  private static final MarshallingFormat FORMAT = MarshallingFormat.JSON;

  private static KieServicesConfiguration conf;
  private static KieServicesClient kieServicesClient;

  public static void initializeKieServerClient() {
        conf = KieServicesFactory.newRestConfiguration(URL, USER, PASSWORD);
        conf.setMarshallingFormat(FORMAT);
        kieServicesClient = KieServicesFactory.newKieServicesClient(conf);
    }

  public void executeCommands() {

    String containerId = "hello";
    System.out.println("== Sending commands to the server ==");
    RuleServicesClient rulesClient = kieServicesClient.getServicesClient(RuleServicesClient.class);
    KieCommands commandsFactory = KieServices.Factory.get().getCommands();

    Command<?> insert = commandsFactory.newInsert("Some String OBJ");
    Command<?> fireAllRules = commandsFactory.newFireAllRules();
    Command<?> batchCommand = commandsFactory.newBatchExecution(Arrays.asList(insert, fireAllRules));

    ServiceResponse<ExecutionResults> executeResponse = rulesClient.executeCommandsWithResults(containerId, batchCommand);

    if(executeResponse.getType() == ResponseType.SUCCESS) {
      System.out.println("Commands executed with success! Response: ");
      System.out.println(executeResponse.getResult());
    } else {
      System.out.println("Error executing rules. Message: ");
      System.out.println(executeResponse.getMsg());
    }
  }
}

所以我对如何将这个TimedRuleExecutionOption传递给会话感到有些困惑?

我已经找到了通过定期发送FireAllRules命令的解决方法,但是我想知道是否可以配置此会话选项,这样我就不必为要创建的每个定时事件添加定期触发。

此外,我尝试使用FireUntilHalt代替FireAllRules,但据我了解,该命令会阻塞服务器上的执行线程,因此我必须在某个时候发送HaltCommand,我希望避免所有这些操作,因为将事件发送到服务器的多线程客户端。

2 个答案:

答案 0 :(得分:0)

您可以使用drools cron功能。它充当计时器,并基于cron表达式调用规则。每5分钟执行一条规则的示例:

rule "Send SMS every 5 minutes"
    timer (cron:* 0/5 * * * ?)
when
    $a : Event( )
then

end

您可以找到说明here

答案 1 :(得分:0)

在启动部署了kie-server.war的服务器实例时,

传递“ -Ddrools.timedRuleExecution = true”。