介绍
QLExpress脚本引擎
1、线程安全,引擎运算过程中的产生的临时变量都是threadlocal类型。
2、高效执行,比较耗时的脚本编译过程可以缓存在本地机器,运行时的临时变量创建采用了缓冲池的技术,和groovy性能相当。
3、弱类型脚本语言,和groovy,javascript语法类似,虽然比强类型脚本语言要慢一些,但是使业务的灵活度大大增强。
4、安全控制,可以通过设置相关运行参数,预防死循环、高危系统api调用等情况。
5、代码精简,依赖最小,250k的jar包适合所有java的运行环境,在android系统的低端pos机也得到广泛运用。
引入
<dependency><groupId>com.alibaba</groupId><artifactId>QLExpress</artifactId><version>3.3.1</version>
</dependency>
案例
简单表达式
public static void testSimple() throws Exception {ExpressRunner runner = new ExpressRunner();IExpressContext<String, Object> context = new DefaultContext<String, Object>();// 设置变量context.put("a", 0);context.put("b", 20);// 定义QLExpress表达式String expression = "a == 0";// 执行表达式Object result = runner.execute(expression, context, null, true, false);// 输出结果System.out.println("Result: " + result);}
动态表达式
public static void testDyExpress() throws Exception {ExpressRunner runner = new ExpressRunner();IExpressContext<String, Object> context = new DefaultContext<String, Object>();// 设置变量context.put("a", 10);context.put("b", 20);// 定义表达式String expression = "a + b * x";// 设置动态变量context.put("x", 2);long s = System.currentTimeMillis();// 执行表达式Object result = runner.execute(expression, context, null, false, false);// 输出结果System.out.println("Result: " + result + "time " + (System.currentTimeMillis() - s));}
自定义方法
自己集成Operator 实现AverageOperator
public class AverageOperator extends Operator {public AverageOperator(String name) {this.name = name;}@Overridepublic Object executeInner(Object[] list) throws Exception {// 获取传递给自定义方法的参数列表double num1 = Double.parseDouble(list[0].toString());double num2 = Double.parseDouble(list[1].toString());// 计算平均值double average = (num1 + num2) / 2;// 返回结果return average;}
}
public static void testCustomMethod() throws Exception {ExpressRunner runner = new ExpressRunner();IExpressContext<String, Object> context = new DefaultContext<String, Object>();// 设置变量context.put("a", 10);context.put("b", 20);// 定义表达式String expression = "average(a, b)";// 注册自定义方法runner.addFunction("average", new AverageOperator("average"));// 执行表达式Object result = runner.execute(expression, context, null, false, false);// 输出结果System.out.println("Result: " + result);}
自动义规则
同自定义方法实现
class IsAdultOperator extends Operator {public IsAdultOperator(String name) {this.name = name;}@Overridepublic Object executeInner(Object[] list) throws Exception {int age = Integer.parseInt(list[0].toString());return age >= 18;
public static void testCustomRule() throws Exception {// 创建ExpressRunner实例ExpressRunner runner = new ExpressRunner();// 注册自定义方法runner.addFunction("isAdult", new IsAdultOperator("isAdult"));// 创建规则String rule = "if isAdult(age) then result = '成年人'; else result = '未成年人'; end";// 创建上下文IExpressContext<String, Object> context = new DefaultContext<>();context.put("age", 18);// 执行规则runner.execute(rule, context, null, true, false);// 获取结果Object result = context.get("result");// 输出结果System.out.println("Result: " + result);}
执行结果
参考
QLExpress