Camunda 7.16 与 Spring Boot 3.x 集成实战:5分钟完成流程引擎嵌入与 REST API 调用
Camunda 7.16 与 Spring Boot 3.x 集成实战5分钟完成流程引擎嵌入与 REST API 调用在当今企业级应用开发中业务流程自动化已成为提升效率的关键。Camunda作为一款轻量级、高性能的开源工作流引擎与Spring Boot的完美结合能够为开发者提供快速实现复杂业务流程的能力。本文将带您从零开始在Spring Boot 3.x项目中集成Camunda 7.16社区版并通过REST API快速启动第一个流程实例。1. 环境准备与依赖配置首先创建一个全新的Spring Boot 3.x项目推荐使用Spring Initializrhttps://start.spring.io生成项目骨架。确保选择的Java版本为17或以上这是Spring Boot 3.x的最低要求。在pom.xml中添加Camunda的核心依赖dependencies !-- Spring Boot Starter -- dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency !-- Camunda核心依赖 -- dependency groupIdorg.camunda.bpm.springboot/groupId artifactIdcamunda-bpm-spring-boot-starter/artifactId version7.16.0/version /dependency !-- 可选REST API支持 -- dependency groupIdorg.camunda.bpm.springboot/groupId artifactIdcamunda-bpm-spring-boot-starter-rest/artifactId version7.16.0/version /dependency !-- 数据库支持以H2为例 -- dependency groupIdcom.h2database/groupId artifactIdh2/artifactId scoperuntime/scope /dependency /dependencies提示Camunda需要数据库支持来持久化流程定义和实例数据。在生产环境中建议使用MySQL、PostgreSQL等更稳定的数据库。2. 基础配置在application.yml中添加Camunda的基本配置spring: datasource: url: jdbc:h2:mem:camunda;DB_CLOSE_DELAY-1 username: sa password: driver-class-name: org.h2.Driver jpa: hibernate: ddl-auto: update camunda: bpm: admin-user: id: admin password: admin filter: create: All tasks database: schema-update: true auto-deployment-enabled: true关键配置说明配置项说明推荐值spring.datasource.url数据库连接URL根据实际数据库调整camunda.bpm.admin-user管理员账号生产环境务必修改camunda.bpm.database.schema-update自动更新数据库Schematrue(开发)/false(生产)camunda.bpm.auto-deployment-enabled自动部署流程定义true3. 部署第一个BPMN流程在src/main/resources目录下创建processes文件夹然后新建一个简单的请假流程leave-request.bpmn?xml version1.0 encodingUTF-8? bpmn:definitions xmlns:bpmnhttp://www.omg.org/spec/BPMN/20100524/MODEL xmlns:bpmndihttp://www.omg.org/spec/BPMN/20100524/DI idDefinitions_1 targetNamespacehttp://bpmn.io/schema/bpmn bpmn:process idleaveRequest nameLeave Request Process isExecutabletrue bpmn:startEvent idStartEvent_1 bpmn:outgoingSequenceFlow_1/bpmn:outgoing /bpmn:startEvent bpmn:sequenceFlow idSequenceFlow_1 sourceRefStartEvent_1 targetRefTask_1 / bpmn:userTask idTask_1 nameSubmit Leave Request bpmn:incomingSequenceFlow_1/bpmn:incoming bpmn:outgoingSequenceFlow_2/bpmn:outgoing /bpmn:userTask bpmn:sequenceFlow idSequenceFlow_2 sourceRefTask_1 targetRefTask_2 / bpmn:userTask idTask_2 nameManager Approval bpmn:incomingSequenceFlow_2/bpmn:incoming bpmn:outgoingSequenceFlow_3/bpmn:outgoing /bpmn:userTask bpmn:sequenceFlow idSequenceFlow_3 sourceRefTask_2 targetRefEndEvent_1 / bpmn:endEvent idEndEvent_1 bpmn:incomingSequenceFlow_3/bpmn:incoming /bpmn:endEvent /bpmn:process bpmndi:BPMNDiagram idBPMNDiagram_1 !-- 省略图形布局定义 -- /bpmndi:BPMNDiagram /bpmn:definitions启动应用后Camunda会自动检测并部署processes目录下的BPMN文件。您可以通过以下URL访问Camunda的管理界面Cockpit: http://localhost:8080/camunda/app/cockpit/default/Tasklist: http://localhost:8080/camunda/app/tasklist/default/4. 通过Java API操作流程引擎创建一个服务类来封装常用的流程操作Service public class CamundaService { Autowired private RuntimeService runtimeService; Autowired private TaskService taskService; Autowired private RepositoryService repositoryService; // 启动流程实例 public String startProcess(String processDefinitionKey, MapString, Object variables) { ProcessInstance instance runtimeService.startProcessInstanceByKey(processDefinitionKey, variables); return instance.getId(); } // 查询用户任务 public ListTask getUserTasks(String assignee) { return taskService.createTaskQuery() .taskAssignee(assignee) .list(); } // 完成任务 public void completeTask(String taskId, MapString, Object variables) { taskService.complete(taskId, variables); } // 部署BPMN文件 public Deployment deployBpmnFile(String resourceName, InputStream inputStream) { return repositoryService.createDeployment() .addInputStream(resourceName, inputStream) .deploy(); } }5. 通过REST API操作流程引擎Camunda提供了完整的REST API支持。以下是使用Spring的RestTemplate调用API的示例RestController RequestMapping(/api/process) public class ProcessController { Autowired private RestTemplate restTemplate; private static final String CAMUNDA_ENGINE_URL http://localhost:8080/engine-rest; // 启动流程实例 PostMapping(/start/{processDefinitionKey}) public ResponseEntity? startProcess( PathVariable String processDefinitionKey, RequestBody MapString, Object variables) { String url CAMUNDA_ENGINE_URL /process-definition/key/ processDefinitionKey /start; MapString, Object request new HashMap(); request.put(variables, variables); return restTemplate.postForEntity(url, request, String.class); } // 查询任务 GetMapping(/tasks) public ResponseEntity? getTasks(RequestParam String assignee) { String url CAMUNDA_ENGINE_URL /task?assignee assignee; return restTemplate.getForEntity(url, String.class); } // 完成任务 PostMapping(/complete/{taskId}) public ResponseEntity? completeTask( PathVariable String taskId, RequestBody MapString, Object variables) { String url CAMUNDA_ENGINE_URL /task/ taskId /complete; MapString, Object request new HashMap(); request.put(variables, variables); return restTemplate.postForEntity(url, request, String.class); } }6. 测试与验证创建一个测试Controller来验证我们的集成RestController RequestMapping(/test) public class TestController { Autowired private CamundaService camundaService; PostMapping(/leave) public String applyLeave(RequestBody MapString, Object request) { // 启动请假流程 String processInstanceId camundaService.startProcess( leaveRequest, Map.of( employee, request.get(employee), days, request.get(days), reason, request.get(reason) ) ); return Leave process started with ID: processInstanceId; } GetMapping(/tasks/{assignee}) public ListMapString, Object getTasks(PathVariable String assignee) { return camundaService.getUserTasks(assignee).stream() .map(task - Map.of( id, task.getId(), name, task.getName(), created, task.getCreateTime() )) .collect(Collectors.toList()); } PostMapping(/complete/{taskId}) public String completeTask( PathVariable String taskId, RequestBody MapString, Object decision) { camundaService.completeTask(taskId, decision); return Task taskId completed; } }使用curl或Postman测试API# 启动请假流程 curl -X POST http://localhost:8080/test/leave \ -H Content-Type: application/json \ -d {employee:john,days:3,reason:Family event} # 查询john的任务 curl http://localhost:8080/test/tasks/john # 完成提交请假申请任务 curl -X POST http://localhost:8080/test/complete/{taskId} \ -H Content-Type: application/json \ -d {approved:true,comments:Approved}7. 高级配置与优化对于生产环境还需要考虑以下配置数据库连接池配置在application.yml中spring: datasource: hikari: maximum-pool-size: 20 minimum-idle: 5 idle-timeout: 30000 max-lifetime: 1800000 connection-timeout: 30000异步执行配置Configuration public class CamundaAsyncConfig { Bean public ProcessEnginePlugin asyncConfiguration() { return new AbstractProcessEnginePlugin() { Override public void preInit(ProcessEngineConfigurationImpl configuration) { configuration.setJobExecutorActivate(true); configuration.setJobExecutorDeploymentAware(true); } }; } }性能监控配置Configuration public class CamundaMetricsConfig { Bean public ProcessEnginePlugin metricsPlugin() { return new MetricsPlugin(); } Bean public MeterRegistry meterRegistry() { return new SimpleMeterRegistry(); } }通过以上步骤您已经成功在Spring Boot 3.x项目中集成了Camunda 7.16并实现了基本的流程管理和REST API调用。这种集成方式既保持了Spring Boot的简洁性又充分利用了Camunda强大的流程引擎能力。

相关新闻