文章目錄
- 1.背景
- 2.簡介
- 3.QLExpress實戰
- 3.1 基礎例子
- 3.2 低代碼實戰
- 3.2.1 需求描述
- 3.2.1 使用規則引擎
- 3.3.2 運行結果
- 參考文檔
1.背景
最近研究低代碼實現后端業務邏輯相關功能,使用LiteFlow作為流程編排后端service服務, 但是LiteFlow官方未提供圖形界面編排流程。且LiteFlow語法對于,通過使用json來定義流程的可視化也不夠友好(二開麻煩)。因此嘗試使用LiteFlow底層使用的是QLExpress,來實現可視化邏輯編排。本文記錄研究過程及其一些功能總結。
2.簡介
什么是QLExpress腳本引擎?
QLExpress(Quick Language Express)是阿里巴巴開源的一門動態腳本引擎解析工具,起源于阿里巴巴的電商業務,旨在解決業務規則、表達式、數學計算等動態腳本的解析問題。
3.QLExpress實戰
maven依賴配置
<!--規則引擎--><dependency><groupId>com.alibaba</groupId><artifactId>QLExpress</artifactId><version>3.2.0</version></dependency>
3.1 基礎例子
ExpressRunner runner = new ExpressRunner();
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
context.put("a", 1);
context.put("b", 2);
context.put("c", 3);
String express = "a + b * c";
Object r = runner.execute(express, context, null, true, false);
System.out.println(r);
3.2 低代碼實戰
模擬低代碼中動態if功能
3.2.1 需求描述
要實現不硬編碼,動態執行包含if的程序邏輯。必須使用聲明式可復用數據結構,如下json定義
{"rule": {"condition": "age > 18","actions": {"allow": "accessGranted","deny": "accessDenied"}},"parameters": {"age": 20}
}
- rule: 規則定義部分, 包含條件節點和執行節點
- parameters: 定義參數部分,定義參數名稱及默認值
執行過程:
- 低代碼引擎解析規則部分,轉化未低成腳本語言
- 讀取從入參中讀取流程變量配置,設置上下文
- 執行運算并獲取結果
下面使用springboot項目具體實現
3.2.1 使用規則引擎
@Service
public class QLExpressTestService {public Map<String, Object> testIf(Map<String, Object > rule, Map<String, Object > parameters) throws Exception {// 根據 Map 對象動態生成 QLExpress 表達式String condition = (String) rule.get("condition");Map<String, String> actionsMap = (Map<String, String>) rule.get("actions");String allowAction = actionsMap.get("allow");String denyAction = actionsMap.get("deny");// 定義 allowAccess 和 denyAccess 方法String qlExpress = "function accessGranted() { return \"Access granted\"; }" +"function accessDenied() { return \"Access denied\"; }" +"if (" + condition + ") { result = " + allowAction + "; } else { result = " + denyAction + "; }";// 執行 QLExpress 表達式ExpressRunner runner = new ExpressRunner();DefaultContext<String, Object> context = new DefaultContext<>();context.put("age", parameters.getOrDefault("age", 20)); // 設置年齡為20歲Object result = runner.execute(qlExpress, context, null, true, false);System.out.println("Result: " + result);return Map.of("scriptContext", qlExpress, "result", result);}
}
3.3.2 運行結果
參考文檔
- https://github.com/alibaba/QLExpress (官網)
- QLExpress學習使用總結-CSDN博客