Spring Boot与Flowable工作流引擎深度整合实战
企业级应用开发中,业务流程管理始终是核心挑战之一。去年参与某跨国零售集团的库存管理系统重构时,我们曾面临审批流程混乱、状态追踪困难等问题,直到引入Flowable工作流引擎才彻底改变了局面。本文将分享如何通过Spring Boot快速整合这一强大工具,并构建一个完整的请假审批流程。
1. 环境准备与基础配置
在开始之前,确保你的开发环境满足以下条件:
- JDK 11或更高版本
- Spring Boot 2.7.x
- MySQL 5.7+/PostgreSQL 12+
- Maven或Gradle构建工具
核心依赖配置对于Maven项目,在pom.xml中添加:
<dependency>
<groupId>org.flowable</groupId>
<artifactId>flowable-spring-boot-starter</artifactId>
<version>6.7.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
对于生产环境,建议替换H2为正式数据库驱动。在application.yml中配置数据库连接:
spring:
datasource:
url: jdbc:mysql://localhost:3306/flowable-demo
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
注意:Flowable启动时会自动创建28张表,建议专门为工作流创建独立数据库
2. 流程建模与BPMN设计
业务流程建模标记语言(BPMN)是Flowable的核心。使用Eclipse BPMN2.0插件或在线工具如bpmn.io设计请假流程:
- 开始事件:流程触发点
- 用户任务:员工提交申请
- 审批节点:组长审批(含网关分支)
- 服务任务:拒绝时的通知处理
- 结束事件:流程终止
典型的请假流程XML定义示例:
<process id="leave-process" name="请假流程" isExecutable="true">
<startEvent id="startEvent"/>
<userTask id="applyLeave" name="请假申请" flowable:assignee="${applicant}"/>
<sequenceFlow sourceRef="startEvent" targetRef="applyLeave"/>
<userTask id="leaderApprove" name="部门审批" flowable:candidateGroups="dept_leader"/>
<sequenceFlow sourceRef="applyLeave" targetRef="leaderApprove"/>
<exclusiveGateway id="decisionGateway"/>
<sequenceFlow sourceRef="leaderApprove" targetRef="decisionGateway"/>
<sequenceFlow id="approvedFlow" sourceRef="decisionGateway" targetRef="hrRecord">
<conditionExpression xsi:type="tFormalExpression">
${approvalResult == 'approved'}
</conditionExpression>
</sequenceFlow>
<serviceTask id="rejectAction" flowable:class="com.example.LeaveRejectService"/>
<sequenceFlow id="rejectedFlow" sourceRef="decisionGateway" targetRef="rejectAction">
<conditionExpression xsi:type="tFormalExpression">
${approvalResult == 'rejected'}
</conditionExpression>
</sequenceFlow>
</process>
将文件保存为leave-process.bpmn20.xml置于resources/processes/目录下,Spring Boot启动时会自动部署。
3. 核心服务交互实战
Flowable通过六大服务接口提供完整API:
| 服务类型 | 作用域 | 典型方法示例 |
|---|---|---|
| RepositoryService | 流程定义与部署 | createDeployment(), getProcessDefinition() |
| RuntimeService | 流程实例控制 | startProcessInstanceByKey(), setVariable() |
| TaskService | 任务处理 | complete(), claim() |
| HistoryService | 历史数据查询 | createHistoricProcessInstanceQuery() |
| ManagementService | 引擎管理 | getTableCount(), executeCustomSql() |
| IdentityService | 用户与组管理 | createUserQuery(), checkPassword() |
流程启动示例:
@Autowired
private RuntimeService runtimeService;
public String startLeaveProcess(String employeeId, int leaveDays, String reason) {
Map<String, Object> variables = new HashMap<>();
variables.put("applicant", employeeId);
variables.put("leaveDays", leaveDays);
variables.put("reason", reason);
ProcessInstance instance = runtimeService.startProcessInstanceByKey(
"leave-process",
variables
);
return instance.getId();
}
任务处理代码:
@Autowired
private TaskService taskService;
public void approveLeave(String taskId, String approver, boolean isApproved) {
Map<String, Object> vars = new HashMap<>();
vars.put("approvalResult", isApproved ? "approved" : "rejected");
vars.put("approver", approver);
vars.put("approvalTime", new Date());
taskService.complete(taskId, vars);
}
4. 高级特性与生产实践
4.1 异步任务处理
对于耗时操作,配置服务任务为异步:
<serviceTask id="notifyHR"
flowable:class="com.example.HRNotificationService"
flowable:async="true"/>
在application.yml中配置执行器:
flowable:
async-executor:
activate: true
core-pool-size: 5
max-pool-size: 10
4.2 历史数据优化
默认情况下Flowable会记录所有历史数据,生产环境建议调整:
flowable:
history-level: audit # 可选none/activity/audit/full
db-history-used: true
对于历史数据量大的系统,可定期归档:
-- 创建归档表
CREATE TABLE ACT_HI_PROCINST_ARCH LIKE ACT_HI_PROCINST;
-- 数据迁移
INSERT INTO ACT_HI_PROCINST_ARCH
SELECT * FROM ACT_HI_PROCINST
WHERE END_TIME_ < DATE_SUB(NOW(), INTERVAL 1 YEAR);
4.3 多租户支持
Flowable提供完善的租户隔离方案:
// 部署时指定租户
repositoryService.createDeployment()
.tenantId("tenant_A")
.addClasspathResource("processes/leave.bpmn20.xml")
.deploy();
// 查询时过滤
runtimeService.createProcessInstanceQuery()
.tenantId("tenant_A")
.list();
5. 调试与性能优化
常见问题排查清单:
- 流程定义未部署 → 检查bpmn文件位置和命名
- 任务分配人无效 → 验证用户/组是否存在
- 变量类型不匹配 → 确保EL表达式中的变量类型正确
- 事务未提交 → 检查@Transactional注解
性能优化建议:
- 为ACT_RU_TASK表的PROC_INST_ID_字段添加索引
- 限制历史数据级别
- 对高频查询使用缓存:
@Cacheable("processDefinitions")
public ProcessDefinition getLatestProcessDefinition(String key) {
return repositoryService.createProcessDefinitionQuery()
.processDefinitionKey(key)
.latestVersion()
.singleResult();
}
在电商订单履约系统的实际案例中,通过优化网关条件和异步服务任务,我们将平均流程处理时间从1200ms降低到400ms。
1310



被折叠的 条评论
为什么被折叠?



