Java端集成drools6.4.0.Final

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		 xmlns="http://java.sun.com/xml/ns/javaee" 
		 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
							 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
		id="WebApp_ID"
		version="3.0">
	
	<display-name>drools-zemo-url</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
  	
  	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
  	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/conf/mvc.xml</param-value>
	</context-param>
	
</web-app>

mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<import resource="classpath:spring.xml" />

</beans>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:kie="http://drools.org/schema/kie-spring"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
						   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
						   http://drools.org/schema/kie-spring 
						   https://raw.githubusercontent.com/droolsjbpm/droolsjbpm-integration/master/kie-spring/src/main/resources/org/kie/spring/kie-spring-6.0.0.xsd
						   http://www.springframework.org/schema/context 
              			   http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	
	<context:component-scan base-package="org.drools.wb.client"/>
	
</beans>
conf.properties

#drools workbench maven2地址
rulejardownload.droolsworkbench.maven2=http://139.217.37.217:8080/kie/maven2
#drools workbench 用户名
rulejardownload.droolsworkbench.username=admin
#drools workbench 密码
rulejardownload.droolsworkbench.password=admin
#规则包定期下载,规则包urls,单个或多个,以“,”间隔。workbench必须以SNAPSHOT方式发布,即不得升级version。
rulejardownload.download.url=/finance/demo/1.7/demo-1.7.jar
#规则包定期下载,启动延迟时间,单位秒
rulejardownload.scheduler.delay=5
#规则包定期下载,任务间隔执行时间,需要根据业务需要设定,单位分钟
rulejardownload.scheduler.period=5



Cst.java

package org.leveret.core.ctx;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.leveret.core.util.Chk;

/**
 * 从Workbench下载规则包,常量类
 * @author 
 */
public final class Cst {

	private static final Logger log = LogManager.getLogger(Cst.class);
	private static final String[] ks = {"rulejardownload.droolsworkbench.maven2",
										"rulejardownload.droolsworkbench.username",
										"rulejardownload.droolsworkbench.password",
										"rulejardownload.download.url",
										"rulejardownload.scheduler.delay",
										"rulejardownload.scheduler.period"
										};
	
	public static final String mvn = Ctx.getStr(ks[0]);
	public static final String user = Ctx.getStr(ks[1]);
	public static final String ps = Ctx.getStr(ks[2]);
	public static final String url = Ctx.getStr(ks[3]);
	public static final long delay = Ctx.getLong(ks[4]);
	public static final long period = Ctx.getLong(ks[5]);
	
	private static boolean isSysReady = true;
	static{
		confChk(ks, new String[]{mvn,
								 user,
								 ps,
								 url,
								 String.valueOf(delay),
								 String.valueOf(period),
								});
		if(!isSysReady) 
			System.exit(0);
	}
	
	private static void confChk(String[] k, String[] v) {
		for(int i=0; i<v.length; i++){
			if(Chk.isEmpty(v[i])){
				isSysReady = false;
				log.fatal("!!! 配置项为空,不能启动:"+ k[i]);
			}
		}
	}
	
}

Ctx.java

package org.leveret.core.ctx;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 上下文环境
 * @author 
 */
public final class Ctx {

	private static final Logger log = LogManager.getLogger(Ctx.class);
	private static PropertiesConfiguration conf;
	
	static{
		try {
			conf = new PropertiesConfiguration("conf.properties");
			conf.setReloadingStrategy(new FileChangedReloadingStrategy());
		} catch (Exception e) {
			log.fatal("!!! 系统找不到配置文件,不能启动:config.properties");
			System.exit(0);
		}
	}
	
	public static String getStr(String k){
		return conf.getString(k);
	}
	
	public static int getInt(String k){
		return conf.getInt(k);
	}
	
	public static long getLong(String k){
		return conf.getLong(k);
	}

}

Chk.java

package org.leveret.core.util;

/**
 * 校验
 * @author 
 */
public final class Chk {
	
	public static boolean isEmpty(String v) {
		return v==null||v.trim().equals("");
	}
	
	public static boolean hasEmpty(String[] vs) {
		for(String v : vs)
			if(isEmpty(v))
				return true;
		return false;
	}
	
	public static boolean isEmpty(Object v) {
		return v==null;
	}
}



RuleJarDownLoadScheduler.java

package org.drools.wb.client.url;

import java.util.Timer;

import org.leveret.core.ctx.Cst;
import org.springframework.stereotype.Component;

/**
 * 从Workbench定期下载规则包,调度,守护
 * @author 
 */
@Component("scheduler")
public final class RuleJarDownLoadScheduler {
	
	static{
//		new Timer(true).schedule(new RuleJarDownLoadTask(), Cst.delay*1000, Cst.period*60*1000);
		new Timer(true).schedule(new RuleJarDownLoadTask(), Cst.delay*1000, Cst.period*1000);
	}
	
}

RuleJarDownLoadTask.java

package org.drools.wb.client.url;

import java.util.TimerTask;

/**
 * 从Workbench定期下载规则包,任务
 * @author 
 */
public final class RuleJarDownLoadTask extends TimerTask {
	
	@Override
	public void run() {
		new RuleJarDownLoader().download();
	}

}

RuleJarDownLoader.java

package org.drools.wb.client.url;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.drools.core.io.impl.UrlResource;
import org.leveret.core.ctx.Cst;
import org.leveret.core.util.Chk;

public class RuleJarDownLoader {

	private static final Logger log = LogManager.getLogger(RuleJarDownLoader.class);
	private static UrlResource ur;
	private static long prevModified = 0;
	
	public void download(){
		try {
			connect();
			if(first())
				notifyKieCreate(ur);
			if(!first() && modified())
				notifyKieUpdate(ur);
		} catch (Exception e) {
			log.fatal("!!! 规则包下载出错:"+e.getMessage()+" !!!");
		} 
	}
	
	private static void connect() throws Exception{
		if(Chk.isEmpty(ur)){
			ur = (UrlResource)Kie.krs.newUrlResource(Cst.mvn + Cst.url);
			ur.setUsername(Cst.user);
			ur.setPassword(Cst.ps);
			ur.setBasicAuthentication("enabled");
		}
	}
	
	private boolean modified(){
		return ur.getLastModified() > prevModified;
	}
	
	private boolean first() {
		return prevModified == 0;
	}
	
	private void notifyKieCreate(UrlResource ur) throws Exception {
		Kie.notifyKieCreate(ur);
		prevModified = ur.getLastModified();
		System.out.println(prevModified);
	}
	
	private void notifyKieUpdate(UrlResource ur) throws Exception {
		Kie.notifyKieUpdate(ur);
		prevModified = ur.getLastModified();
		System.out.println(prevModified);
	}
	
}

Kie.java

package org.drools.wb.client.url;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.drools.core.io.impl.UrlResource;
import org.kie.api.KieServices;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.KieRepository;
import org.kie.api.io.KieResources;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.springframework.stereotype.Component;

/**
 * 基于URL创建Kie
 * @author 
 */
@Component("urlkie")
public class Kie {
	
	private static final Logger log = LogManager.getLogger(Kie.class);
	private static final KieServices ks = KieServices.Factory.get();
	private static final KieRepository kr = ks.getRepository();
	protected static final KieResources krs = ks.getResources();
	private static KieModule km;
	private static KieContainer kc;
    private static StatelessKieSession ksl;
	private static KieSession ksf;
	
	public static void exec(Object obj) {
		try {
			ksl.execute(obj);
		} catch (Exception e) {
			log.fatal("!!! url KieSession执行出错:"+e.getMessage()+" !!!");
		} 
	}
	
	public static void notifyKieCreate(UrlResource ur) {
		try {
			km = kr.addKieModule(krs.newInputStreamResource(ur.getInputStream()));
			kc = ks.newKieContainer(km.getReleaseId());
			ksl = kc.newStatelessKieSession(); 
		} catch (Exception e) {
			log.fatal("!!! url 创建KieSession出错:"+e.getMessage()+" !!!");
		} 
	}
	
	public static void notifyKieUpdate(UrlResource ur) {
		try {
			kr.removeKieModule(km.getReleaseId());
			notifyKieCreate(ur);
		} catch (Exception e) {
			log.fatal("!!! url 重新创建KieSession出错:"+e.getMessage()+" !!!");
		} 
	}

}

在workbench新建项目编辑 dataobject和drl,打包发布,java端即可调用。举例如下:

what.drl

package finance.demo;

no-loop

rule "female romeo"
  when
    m:Human(gender==1);
  then
    modify(m){setName("romeo-what-1.777")};
end

rule "male juliet"
  when
    m:Human(gender==0)
  then
    modify(m){setName("juliet-what-1.777")}
end

Human.java

package finance.demo;

/**
 * This class was automatically generated by the data modeler tool.
 */

public class Human implements java.io.Serializable
{

   static final long serialVersionUID = 1L;

   private java.lang.Long id;
   private java.lang.String name;
   private int gender;

   public Human()
   {
   }

   public java.lang.Long getId()
   {
      return this.id;
   }

   public void setId(java.lang.Long id)
   {
      this.id = id;
   }

   public java.lang.String getName()
   {
      return this.name;
   }

   public void setName(java.lang.String name)
   {
      this.name = name;
   }

   public int getGender()
   {
      return this.gender;
   }

   public void setGender(int gender)
   {
      this.gender = gender;
   }

   public Human(java.lang.Long id, java.lang.String name, int gender)
   {
      this.id = id;
      this.name = name;
      this.gender = gender;
   }

}

TestServlet.java
package test.kie.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import finance.demo.Human;

@WebServlet(urlPatterns={"/init"}) 
public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
//	@Autowired
//	Kie springkie; 

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("get servlet ok");
		
		
		Human v1 = new Human();
		
		v1.setGender(1);
		org.drools.wb.client.url.Kie.exec(v1);
		System.out.println("=="+v1.getName());
		
		v1.setGender(0);
		org.drools.wb.client.url.Kie.exec(v1);
		System.out.println("=="+v1.getName());
		
		v1.setGender(2);
		org.drools.wb.client.url.Kie.exec(v1);
		System.out.println("=="+v1.getName());
		
		v1.setGender(3);
		org.drools.wb.client.url.Kie.exec(v1);
		System.out.println("=="+v1.getName());
		
		System.out.println("url ok");
		
//		Human v2 = new Human();
//		v2.setGender(1);
//		org.drools.wb.client.mvn.Kie.exec(v2);
//		System.out.println("=="+v2.getName());
//		System.out.println("mvn ok");
		
		
//		ApplicationContext cxt = new ClassPathXmlApplicationContext("spring.xml");
//		ApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(((HttpServletRequest)req).getSession().getServletContext());
//		org.drools.wb.client.spring.Kie kie = (org.drools.wb.client.spring.Kie)cxt.getBean("springkie");
//		Human v3 = new Human();
//		v3.setGender(1);
//		kie.exec(v3);
//		System.out.println("=="+v3.getName());
//		System.out.println("spring ok");
	}
		
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("post servlet ok");
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值