为什么80%的码农都做不了架构师?>>>
jexl表达式解析、计算工具类.md 根据表达式可以动态反向解析出变量;适合动态表达式,参数未知场景 如 (A0.2+B0.8)/C 解析出 A\B\C,把ABC参数值代入计算 初始化引擎
private static final JexlEngine ENGINE = new JexlEngine();
static {
ENGINE.setCache(512);
ENGINE.setLenient(false);
ENGINE.setSilent(false);
}
解析出表达式中的变量 ExpressionUtils
package com.its.cloud.utils;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.ExpressionImpl;
import org.apache.commons.jexl2.JexlEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Created by [email protected] on 2015/1/19.
*/
public class ExpressionUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ExpressionUtils.class);
private static final JexlEngine JEXL = new JexlEngine();
static {
JEXL.setCache(512);
JEXL.setLenient(false);
JEXL.setSilent(false);
}
public static JexlEngine getJexlEngine() {
return JEXL;
}
public static boolean isValidExpression(String expression) {
try {
JEXL.createExpression(expression);
return true;
} catch (Throwable t) {
LOGGER.error("表达式{}配置错误{}。", expression, t.getMessage(), t);
return false;
}
}
/**
* 获取表达式中的变量参数
*
* @param expression 表达式,如 ping.max>0 and ping.min>0 and pin.lost==0
*/
public static List getVariables(String expression) {
Expression exp;
try {
exp = JEXL.createExpression(expression);
} catch (Throwable t) {
LOGGER.error("表达式{}配置错误{}。", expression, t.getMessage(), t);
return Collections.emptyList();
}
return getVariables(exp);
}
public static List getVariables(Expression exp) {
List metricDefIds = Lists.newArrayList();
Set> variables = JEXL.getVariables((ExpressionImpl) exp);
for (List var : variables) {
metricDefIds.add(Joiner.on(".").join(var));
}
return metricDefIds;
}
}
解析变量,调用示例
jexl反向解析表达式中的变量
JexlEngine jexl = new JexlEngine();
String threshold = "(value==3)and (cpu>90 and mem <70)";
Expression exp = jexl.createExpression(threshold);
List variables = jexl.getVariables(((ExpressionImpl)exp));
表达式示例
String threshold = "value>90";
Expression exp = getJexlEngine().createExpression(threshold);
JexlContext jc = new MapContext();
jc.set("value", data.getValue());
Object evaluate = exp.evaluate(jc);
if (evaluate instanceof Boolean) {
return (boolean) evaluate;
} else {
LOGGER.error("表达式错误{},不是boolean返回值;{}", exp, rule);
return false;
}