MVEL表达式引擎使用教程

d_hero
发布于 2023-7-5 14:39
浏览
0收藏

pom.xml引入依赖

 <!-- mvel -->
 <dependency>
    <groupId>org.mvel</groupId>
    <artifactId>mvel2</artifactId>
    <version>2.4.7.Final</version>
</dependency>

自定义方法 mvel

package com.example.demo.util.mvel;

/**
 * 自定义方法 mvel
 */
public class UserFunction {

    /**
     * 第N位为
     * @param data      数据字段 random
     * @param n         N位 80
     * @param value     值 (1,2,3,4) 只要其中一个满足,就返回true
     * @return
     */
    public static boolean nthBitEq(String data, String n, String value) {
        int m = Integer.parseInt(n);
        String tmp = data.substring(m-1, m);
        String[] aars = value.split(",");

        boolean rs = false;
        for (String arr : aars) {
            rs = rs || tmp.equals(arr.trim());
        }
        return rs;
    }

    /**
     * 第N位不为
     * @param data      数据字段 random
     * @param n         N位 80
     * @param value     值 (1,2,3,4) 只要其中一个满足,就返回false
     * @return
     */
    public static boolean nthBitNq(String data, String n, String value) {
        return !nthBitEq(data,n,value);
    }

    /**
     * 第N位介于 [5,8]  >=5 and <=8
     * @param data      数据字段 random
     * @param n         N位 80
     * @param sv        开始值  5
     * @param ev        结束值  8
     * @return
     */
    public static boolean nthBitBt(String data, String n, String sv, String ev) {
        int m = Integer.parseInt(n);
        int tmp = Integer.valueOf(data.substring(m-1, m));
        return tmp >= Integer.valueOf(sv) && tmp <= Integer.valueOf(ev);
    }


    /**
     * 倒数第N位为
     * @param data      数据字段    random
     * @param n         倒数第N位
     * @param value     值(1,2,3,4) 只要其中一个满足,就返回true
     * @return
     */
    public static boolean enBitEq(String data, String n, String value) {
        int m = data.length() - Integer.parseInt(n) + 1;
        String tmp = data.substring(m-1, m);
        String[] airs = value.split(",");

        boolean rs = false;
        for (String arr : airs) {
            rs = rs || tmp.equals(arr.trim());
        }
        return rs;
    }

    /**
     * 倒数第N位不为
     * @param data      数据字段    random
     * @param n         倒数第N位
     * @param value     值(1,2,3,4) 只要其中一个满足,就返回false
     * @return
     */
    public static boolean enBitNq(String data, String n, String value) {
        return !enBitEq(data,n,value);
    }

    /**
     * 倒数第N位介于 [5,8]  >=5 and <=8
     * @param data      数据字段 random
     * @param n         N位 80
     * @param sv        开始值  5
     * @param ev        结束值  8
     * @return
     */
    public static boolean enBitBt(String data, String n, String sv, String ev) {
        int m = data.length() - Integer.parseInt(n) + 1;
        int tmp = Integer.valueOf(data.substring(m-1, m));
        return tmp >= Integer.valueOf(sv) && tmp <= Integer.valueOf(ev);
    }

    /**
     * 尾号为
     * @param data      数据字段    mid
     * @param value     值(1,2,3,4) 只要其中一个满足,就返回true
     * @return
     */
    public static boolean tailEq(String data, String value) {
        String[] airs = value.split(",");
        boolean rs = false;
        for (String arr : airs) {
            rs = rs || data.endsWith(arr.trim());
        }
        return rs;
    }

    /**
     * 尾号不为
     * @param data      数据
     * @param value     值(1,2,3,4) 只要其中一个满足,就返回false
     * @return
     */
    public static boolean tailNq(String data, String value) {
        return !tailEq(data, value);
    }

    /**
     * 尾号介于 [5,8]  >=5 and <=8
     * @param data      数据字段 mid
     * @param sv        开始值  5
     * @param ev        结束值  8
     * @return
     */
    public static boolean tailBt(String data, String sv, String ev) {
        int tmp = Integer.valueOf(data.substring(data.length()-1, data.length()));
        return tmp >= Integer.valueOf(sv) && tmp <= Integer.valueOf(ev);
    }

    /**
     * 包含
     * @param data      数据字段    channel
     * @param value     值(F,D,E)    包含其中之一就返回true
     * @return
     */
    public static boolean defContains(String data, String value) {
        String[] arcs = value.split(",");

        boolean rs = false;
        for (String arr : arcs) {
            rs = rs || data.contains(arr.trim());
        }
        return rs;
    }

    /**
     * 不包含
     * @param data      数据字段    channel
     * @param value     值(F,D,E)    包含其中之一就返回false
     * @return
     */
    public static boolean defNotContains(String data, String value) {
        return !defContains(data, value);
    }


    /**
     * 布尔值为真
     * @param data      数据字段
     */
    public static boolean isTrue(String data) {
        return Boolean.parseBoolean(data);
    }

    /**
     * 布尔值为假
     * @param data      数据字段
     */
    public static boolean isFalse(String data) {
        return !Boolean.parseBoolean(data);
    }

}

Mvel编译

package com.example.demo.util.mvel;
import org.apache.commons.lang3.StringUtils;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * Mvel编译
 */
public class MvelCompiler {

    private static final MvelCompiler instance = new MvelCompiler();

    private static ParserContext context;

    private MvelCompiler() {
        context = new ParserContext();

        // 将UserFunction类中的所有方法加载到context中
        Method[] declaredMethods = UserFunction.class.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            context.addImport(declaredMethod.getName(), declaredMethod);
        }

        // 或者用下面这种一个个指定的方式加载到context中
//        context.addImport("containsIgnCase", MVEL.getStaticMethod(UserFunction.class, "containsIgnCase", new Class[]{String.class, String.class}));
    }

    public static MvelCompiler getInstance() {
        return instance;
    }

    public static ParserContext getContext() {
        return context;
    }

    public Serializable compile(String expression) {
        if (StringUtils.isNotEmpty(expression)) {
            return MVEL.compileExpression(expression, context);
        }

        return null;
    }
}

Mvel执行器

package com.example.demo.util.mvel;

import lombok.extern.slf4j.Slf4j;
import org.mvel2.MVEL;

import java.util.Map;

/**
 * Mvel执行器
 */
@Slf4j
public class MvelExecutor {

    /**
     * 执行
     * @param mvel      mvel表达式
     * @param params    参数
     * @return
     */
    public static Boolean eval(String mvel, Map<String, Object> params) {
        Boolean isPass = null;
        try {
            isPass = (Boolean) MVEL.executeExpression(MVEL.compileExpression(mvel, MvelCompiler.getContext()), params);
        } catch (Exception e) {
            isPass = Boolean.FALSE;
            log.error("解析失败mvel");
        }
        return isPass;
    }

}

Mvel表达式引擎测试类

package com.example.demo.util.mvel;

import java.util.HashMap;

/**
 * 描述:Mvel表达式引擎测试类 </br>
 * 作者:IT学习道场 </br>
 * 时间:2023-02-15 10:52
 */
public class MvelTest {

    private static boolean isTrue(){
        String mvel = "(isTrue(openPlatformStatus))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("openPlatformStatus", true);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    private static boolean isFalse(){
        String mvel = "(isFalse(openPlatformStatus))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("openPlatformStatus", false);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }
    /**
     * 等于
     * @return
     */
    private static boolean evalEquals(){
        String mvel = "(openPlatformStatus==('1'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("openPlatformStatus", 0);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 不等于
     * @return
     */
    private static boolean evalNotEquals(){
        String mvel = "(openPlatformStatus!=('1'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("openPlatformStatus", 0);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }


    /**
     * and
     * @return
     */
    private static boolean evalAnd(){
        String mvel = "(realname==('90')&&sex==('1'))&&(randomNum==('111'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("realname", 90);
        mvelMap.put("sex", 1);
        mvelMap.put("randomNum", 111);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * or
     * @return
     */
    private static boolean evalOr(){
        String mvel = "(realname==('90')||sex==('1'))||(randomNum==('111'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("realname", 91);
        mvelMap.put("sex", 1);
        mvelMap.put("randomNum", 111);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }


    /**
     * 不包含
     * @return true - 不包含,false - 包含
     */
    private static boolean evalNotContains(){
        String mvel = "(defNotContains(userName, '2'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("userName", 92);
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 不包含
     * @return true - 包含,false - 不包含
     */
    private static boolean evalContains(){
        String mvel = "(defContains(userName, '2'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("userName", "92");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     *大于等于
     * @return true - 包含,false - 不包含
     */
    private static boolean evalGt(){
        String mvel = "(age>=('33'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("age", "32");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     *大于
     * @return true - 包含,false - 不包含
     */
    private static boolean evalGe(){
        String mvel = "(age>('33'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("age", "35");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 小于等于
     * @return true - 包含,false - 不包含
     */
    private static boolean evalLt(){
        String mvel = "(age<=('33'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("age", "32");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 小于等于
     * @return true - 包含,false - 不包含
     */
    private static boolean evalLe(){
        String mvel = "(age<('33'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("age", "32");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 尾号不为
     */
    private static boolean evalTailNq(){
        String mvel = "(tailNq(phone, '3334'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("phone", "154854543335");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 尾号为
     */
    private static boolean evalTailEq(){
        String mvel = "(tailEq(phone, '3334'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("phone", "154854543334");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }


    /**
     * 第N位介于
     */
    private static boolean evalNthBitBt(){
        String mvel = "(nthBitBt(randomNum,'3', '5','8'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("randomNum", "154454543334");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 第N位不等于
     */
    private static boolean evalNthBitNq(){
        String mvel = "(nthBitNq(randomNum,'2', '3'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("randomNum", "144454543334");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    /**
     * 第N位等于
     */
    private static boolean evalNthBitEq(){
        String mvel = "(nthBitEq(randomNum,'2', '4'))";
        HashMap<String, Object> mvelMap = new HashMap<>();
        mvelMap.put("randomNum", "144454543334");
        Boolean result = MvelExecutor.eval(mvel, mvelMap);
        System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        evalNthBitEq();
        // evalNthBitNq();
        // evalNthBitBt();
        // evalTailEq();
        // isTrue();
        // isFalse();
        // evalEquals();

        // evalNotEquals();

        // evalAnd();

        // evalOr();

        // evalNotContains();

        // evalContains();

        // evalGt();

        // evalGe();

        // evalLt();
        // evalLe();
        // evalTailNq();

    }

}

完事!可以应用在规则表达式配置,把规则的条件表达式保存到数据库,根据规则获取表达式,和计算或传来的参数,对表达式进行运算,看看是否匹配,匹配是true,不匹配是false




文章转载自公众号:IT学习道场

分类
已于2023-7-5 14:39:10修改
收藏
回复
举报
回复
    相关推荐