在一些規則集或者作業流專案中,經常會遇到動態決議運算式并執行得出結果的功能,
規則引擎是一種嵌入在應用程式中的組件,它可以將業務規則從業務代碼中剝離出來,使用預先定義好的語意規范來實作這些剝離出來的業務規則;規則引擎通過接受輸入的資料,進行業務規則的評估,并做出業務決策,
作業流(Workflow),是對作業流程及其各操作步驟之間業務規則的抽象、概括描述, 作業流建模,即將作業流程中的作業如何前后組織在一起的邏輯和規則,在計算機中以恰當的模型表達并對其實施計算, 作業流要解決的主要問題是:為實作某個業務目標,利用計算機在多個參與者之間按某種預定規則自動傳遞檔案、資訊或者任務,
Table of Contents
目錄- 前綴、中綴、后綴運算式(逆波蘭運算式)
- 中綴運算式
- 后綴運算式
- 前綴運算式
- OGNL
- SpEL
- Jexl/Jexl3
- 執行簡單的運算式
- Groovy
- 執行運算式
- 擴展
- 參考
前綴、中綴、后綴運算式(逆波蘭運算式)
最早接觸的運算式決議是在上資料結構的時候,當時課設作業是 “ 做一個簡單的四則混合運算陳述句決議并計算結果 ”,簡單說就是計算器,
中綴運算式
將運算子寫在兩個運算元中間的運算式,稱作中綴運算式,
中綴運算式是我們最熟悉和閱讀最容易的運算式
比如:12 + 34 + 5 * 6 - 30 / 5
也就是我們常用的數學算式就是用中綴運算式表示的
后綴運算式
將運算子寫在兩個運算元之后的運算式稱作后綴運算式,
12 34 + 5 6 * + 30 5 / -
前綴運算式需要從左往右讀,遇到一個運演算法,則從左邊取 2 個運算元進行運算
從左到右讀則可分為
((12 34 + )(5 6 * )+ )(30 / 5) -
括號只是輔助,實際上沒有
前綴運算式
前綴運算式是將運算子寫在兩個運算元之前的運算式,
前綴運算式需要從右往左讀,遇到一個運演算法,則從右邊取 2 個運算元進行運算
12 + 34 + 5 * 6 - 30 / 5
- + + 12 34 * 5 6 / 30 5
- 中綴:
12 + 34 + 5 * 6 - 30 / 5 - 后綴:
12 34 + 5 6 * + 30 5 / - - 前綴:
- + + 12 34 * 5 6 / 30 5
OGNL
OGNL(Object-Graph Navigation Language的簡稱),物件圖導航語言,它是一門運算式語言,除了用來設定和獲取Java物件的屬性之外,另外提供諸如集合的投影和過濾以及lambda運算式等,
引入依賴
<!-- https://mvnrepository.com/artifact/ognl/ognl -->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.18</version>
</dependency>
MemberAccess memberAccess = new AbstractMemberAccess() {
@Override
public boolean isAccessible(Map context, Object target, Member member, String propertyName) {
int modifiers = member.getModifiers();
return Modifier.isPublic(modifiers);
}
};
OgnlContext context = (OgnlContext) Ognl.createDefaultContext(this,
memberAccess,
new DefaultClassResolver(),
new DefaultTypeConverter());
context.put("verifyStatus", 1);
Object expression = Ognl.parseExpression("#verifyStatus == 1");
boolean result =(boolean) Ognl.getValue(expression, context, context.getRoot());
Assert.assertTrue(result);
SpEL
SpEL(Spring Expression Language),即Spring運算式語言,它是一種類似JSP的EL運算式、但又比后者更為強大有用的運算式語言,
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("#verifyStatus == 1");
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("verifyStatus", 1);
boolean result = (boolean) expression.getValue(context);
Assert.assertTrue(result);
Jexl/Jexl3
引入依賴
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jexl3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl3</artifactId>
<version>3.1</version>
</dependency>
執行簡單的運算式
JexlEngine jexl = new JexlBuilder().create();
JexlContext jc = new MapContext();
jc.set("verifyStatus", 1);
JexlExpression expression = jexl.createExpression("verifyStatus == 1");
boolean result = (boolean) expression.evaluate(jc);
Assert.assertTrue(result);
Groovy
Groovy 是一個很好的選擇,其具備完備的 Groovy 和 Java 語法的決議執行功能,
引入依賴, 這個可以根據需要引入最新版本
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.5.6</version>
</dependency>
執行運算式
Binding binding = new Binding();
binding.setVariable("verifyStatus", 1);
GroovyShell shell = new GroovyShell(binding);
boolean result = (boolean) shell.evaluate("verifyStatus == 1");
Assert.assertTrue(result);
擴展
經常用 MyBatis 的一定用過動態陳述句
<select id="getList"
resultMap="UserBaseMap"
parameterType="com.xx.Param">
select
id, invite_code, phone, name
from user
where status = 1
<if test="_parameter != null">
<if test="inviteCode !=null and inviteCode !='' ">
and invite_code = #{inviteCode}
</if>
</if>
</select>
這里我們簡化一下
該示例主要為了講解,不一定好用, 其中 @if 與上面的 <if> 等效
select id, invite_code, phone, name
from user
where status = 1
@if(:inviteCode != null) { and invite_code = :inviteCode }
在處理這種 SQL 中,我們可以先用正則,將 @if 與 正常陳述句分割開
List<String> results = StringUtil.matches(sql, "@if([\\s\\S]*?)}");
通過這種方式匹配到 @if(:inviteCode != null) { and invite_code = :inviteCode }
然后將需要執行計算的運算式與要拼接的 SQL 分離出
String text = "@if(:inviteCode != null) { and invite_code = :inviteCode }";
List<String> sqlFragment = StringUtil.matches(text, "\\(([\\s\\S]*?)\\)|\\{([\\s\\S]*?)\\}");
分離出
- :inviteCode != null
- and invite_code = :inviteCode
其中 :inviteCode != null 是需要動態處理的陳述句,對于 :inviteCode != null 我們需要識別出,那些是需要進行復制的變數名稱
List<String> sqlFragmentParam = StringUtil.matches(":inviteCode != null", "\\?\\d+(\\.[A-Za-z]+)?|:[A-Za-z0-9]+(\\.[A-Za-z]+)?");
得到 inviteCode,并通過某種方式找到對應的值,
JexlEngine jexl = new JexlBuilder().create();
JexlContext jc = new MapContext();
jc.set(":inviteCode", "ddddsdfa");
JexlExpression expression = jexl.createExpression(sqlExp);
boolean needAppendSQL = (boolean) expression.evaluate(jc);
通過 needAppendSQL 來決定是否拼接 SQL, 這樣一個簡單的動態 SQL 就實作了,上面用的 Jexl 寫的,你可以改成上面任意一種方案,這里只做演示
具體代碼,僅供參考
@Test
public void testSQL() {
String sql = "select id, invite_code, phone, name \n"
+ "from user \n"
+ "where status = 1 \n"
+ "@if(:inviteCode != null) { and invite_code = :inviteCode }";
Map<String, Object> params = new HashMap<String, Object>();
params.put("inviteCode", "dd");
System.out.println(parseJexl(sql, params));
}
public String parseJexl(String jexlSql, Map<String, Object> params) {
// 判斷是否包含 @if
List<String> results = StringUtil.matches(jexlSql, "@if([\\s\\S]*?)}");
if (results.isEmpty()) {
return jexlSql;
}
JexlEngine jexl = new JexlBuilder().create();
JexlContext jc = new MapContext();
for (String e : results) {
List<String> sqlFragment = StringUtil.matches(e, "\\(([\\s\\S]*?)\\)|\\{([\\s\\S]*?)\\}");
String sqlExp = sqlFragment.get(0).trim().substring(1, sqlFragment.get(0).length() - 1);
List<String> sqlFragmentParam = StringUtil.matches(sqlExp, "\\?\\d+(\\.[A-Za-z]+)?|:[A-Za-z0-9]+(\\.[A-Za-z]+)?");
for (String param : sqlFragmentParam) {
String newSQLExp = "_" + param.substring(1);
sqlExp = sqlExp.replace(param, newSQLExp);
jc.set(newSQLExp, params.get(param.substring(1)));
}
JexlExpression expression = jexl.createExpression(sqlExp);
Boolean needAppendSQL = (Boolean) expression.evaluate(jc);
if (needAppendSQL) {
jexlSql = jexlSql.replace(e, sqlFragment.get(1).trim().substring(1, sqlFragment.get(1).length() - 1));
} else {
jexlSql = jexlSql.replace(e, "");
}
}
return jexlSql;
}
參考
關于 OGNL、SpEL、Jexl3 和 Groovy 的具體用法可以參考檔案
- http://commons.apache.org/proper/commons-jexl/reference/syntax.html
- https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
- http://groovy-lang.org/syntax.html
- http://commons.apache.org/proper/commons-ognl/language-guide.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/259924.html
標籤:其他
