当前位置: 首页 > news >正文

SpringBoot3-Flowable7初体验

目录

  • 简介
  • 准备
    • JDK
    • MySQL
    • flowable-ui
  • 创建流程图
    • 要注意的地方
  • 编码
    • 依赖和配置
    • 控制器
    • 实体
    • Flowable任务处理类
  • 验证
    • 启动程序
    • 调用接口
  • 本文源码
  • 参考

简介

  • Flowable是一个轻量的Java业务流程引擎,用于实现业务流程的管理和自动化。相较于老牌的Activiti做了一些改进和扩展,实现更高的性能和更小的内存占用,支持更多的数据库类型。

准备

JDK

  • JDK 17

MySQL

  • flowable程序初始化会生产表,所以要数据库。
  • MySQL 数据库,我使用的是phpstudy(下载地址:https://www.xp.cn/phpstudy#phpstudy)集成环境的MySQL8.0.12

在这里插入图片描述

flowable-ui

  • 需要事先建一个流程给flowable,所以要个可视化界面创建流程。
  • flowable-ui:使用docker安装,使用命令:
 docker run -d --name fu -p 8080:8080 flowable/flowable-ui

在这里插入图片描述

  • 运行起来的网页效果,地址是 http://ip:8080/flowable-ui

默认帐号密码: admin test

在这里插入图片描述

  • 如果拉不下来镜像,请尝试以下方案:
    • 方案一、设置代理,参考拙作Docker设置代理
    • 方案二、更换镜像源,如下配置(编辑/etc/docker/daemon.json):
{"registry-mirrors": ["https://docker.m.daocloud.io"]
}

创建流程图

  • 实现一个创建采购订单,order.totalPrice金额大于1000要经理确认的功能。
    在这里插入图片描述
    在这里插入图片描述
  • 完整流程图
    在这里插入图片描述

要注意的地方

  • 设置分支条件,order.totalPrice大于1000要经理确认。
    在这里插入图片描述

  • 任务要绑定处理类
    在这里插入图片描述
    在这里插入图片描述

  • 经理确认节点要绑定参数 Assignee manager
    在这里插入图片描述
    在这里插入图片描述

编码

依赖和配置

  • 引入的包
		<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId><version>3.5.11</version></dependency><!-- 阿里数据库连接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.23</version></dependency><!-- Mysql驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><dependency><groupId>org.flowable</groupId><artifactId>flowable-spring-boot-starter</artifactId><version>7.1.0</version></dependency>
  • 程序配置文件
spring:application:name: flowable-sampleprofiles:active: dev
server:port: 8080# MyBatis配置
mybatis-plus:# 搜索指定包别名typeAliasesPackage: com.zzq.domain# 配置mapper的扫描,找到所有的mapper.xml映射文件mapperLocations: classpath*:mapper/**/*Mapper.xml# 加载全局的配置文件configLocation: classpath:mybatis/mybatis-config.xml# 日志配置
logging:level:com.zzq: debug
flowable:#  是否激活异步执行器async-executor-activate: false# 数据库模式更新策略,true表示自动更新数据库模式database-schema-update: true
  • application-dev.yml
# 数据源配置
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcedriverClassName: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/flowable_sample?nullCatalogMeansCurrent=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8username: rootpassword: root
  • 下载文件放到项目中resources/processes
    在这里插入图片描述
    在这里插入图片描述
  • FlowableConfig
package com.zzq.config;import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.context.annotation.Configuration;/*** FlowableConfig** @Description: 解决Diagram生成的流程图文字显示为”口口口“ 这是因为本地没有默认的字体,安装字体或者修改配置解决* @Author: zzq* @Date 2025/4/5 15:16* @since 1.0.0*/
@Configuration
public class FlowableConfig implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {@Overridepublic void configure(SpringProcessEngineConfiguration springProcessEngineConfiguration) {springProcessEngineConfiguration.setActivityFontName("宋体");springProcessEngineConfiguration.setLabelFontName("宋体");springProcessEngineConfiguration.setAnnotationFontName("宋体");}
}

控制器

  • OrderFlowController
package com.zzq.controller;import com.zzq.domain.Order;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricActivityInstanceQuery;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;/*** Zhou Zhongqing* 2025-04-01* 订单流程控制器*/
@RestController
@RequestMapping("/orderFlow")
public class OrderFlowController {private static final Logger log = LoggerFactory.getLogger(OrderFlowController.class);@Resourceprivate HistoryService historyService;@Resourceprivate RepositoryService repositoryService;@Resourceprivate RuntimeService runtimeService;@Resourceprivate TaskService taskService;@Resourceprivate ProcessEngine processEngine;/*** 开始流程* @param content* @param totalPrice* @return*/@PostMapping("/create_order")public ResponseEntity<String> startFlow(String content, Integer totalPrice) {Map<String, Object> map = new HashMap<>();map.put("order", new Order(content, totalPrice));ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("flowable-sample", map);String processId = processInstance.getId();log.info("{} 流程实例ID:{} ", processInstance.getProcessDefinitionName(), processId);Task task = taskService.createTaskQuery().processInstanceId(processId).active().singleResult();taskService.complete(task.getId());return ResponseEntity.ok(processId);}/*** 订单列表,待确认的,返回任务id* @return*/@RequestMapping("/order_list")public String getOrderList() {List<Task> list = taskService.createTaskQuery().taskAssignee("manager").list();StringBuffer stringBuffer = new StringBuffer();list.stream().forEach(task -> stringBuffer.append(task.getId()+ " : " + runtimeService.getVariable(task.getExecutionId(), "order") + "\n"));return stringBuffer.toString();}/*** 经理确认* @param taskId* @return*/@PostMapping("/confirm/{taskId}")public ResponseEntity<String> confirm(@PathVariable String taskId) {Task task = taskService.createTaskQuery().taskId(taskId).singleResult();HashMap<String, Object> map = new HashMap<>();map.put("verified", true);taskService.complete(taskId, map);return ResponseEntity.ok("success");}/*** 生成图,某个流程处理进度显示* @param response* @param processId* @throws Exception*/@GetMapping(value = "/processDiagram/{processId}")public void genProcessDiagram(HttpServletResponse response, @PathVariable("processId") String processId) throws Exception{ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();if (null == pi) {return;}Task task = taskService.createTaskQuery().processInstanceId(pi.getId()).singleResult();//使用流程实例ID,查询正在执行的执行对象表,返回流程实例对象String instanceId = task.getProcessInstanceId();List<Execution> executions = runtimeService.createExecutionQuery().processInstanceId(instanceId).list();//得到正在执行的Activity的IdList<String> activityIds = new ArrayList<>();List<String> flows = new ArrayList<>();List<HistoricActivityInstance> historyList = historyService.createHistoricActivityInstanceQuery().processInstanceId(processId).orderByHistoricActivityInstanceStartTime().asc().list();for (HistoricActivityInstance historicActivityInstance : historyList) {String activityId = historicActivityInstance.getActivityId();if("sequenceFlow".equals(historicActivityInstance.getActivityType())){flows.add(activityId);}}for (Execution exe : executions) {List<String> ids = runtimeService.getActiveActivityIds(exe.getId());activityIds.addAll(ids);}// 获取流程图BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());ProcessEngineConfiguration engConf = processEngine.getProcessEngineConfiguration();ProcessDiagramGenerator diagramGenerator = engConf.getProcessDiagramGenerator();String format = "png";InputStream in = diagramGenerator.generateDiagram(bpmnModel, "png", activityIds, flows, engConf.getActivityFontName(), engConf.getLabelFontName(), engConf.getAnnotationFontName(), engConf.getClassLoader(), 1.0, false);
//        OutputStream out = null;
//        byte[] buf = new byte[1024];
//        int legth = 0;
//        try {
//            out = response.getOutputStream();
//            while ((legth = in.read(buf)) != -1) {
//                out.write(buf, 0, legth);
//            }
//        } finally {
//            if (in != null) {
//                in.close();
//            }
//            if (out != null) {
//                out.close();
//            }
//        }IOUtils.copy(in, response.getOutputStream());}}

实体

  • Order
package com.zzq.domain;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;import java.io.Serializable;
import java.io.Serial;
@TableName(value = "t_order")
public class Order implements Serializable {@Serialprivate static final long serialVersionUID = 8347055723013141158L;public Order() {}public Order(String content, Integer totalPrice) {this.content = content;this.totalPrice = totalPrice;}public Order(Integer id, String content, Integer totalPrice) {this.id = id;this.content = content;this.totalPrice = totalPrice;}@TableId(value = "id",type = IdType.AUTO)private Integer id;private String content;private Integer totalPrice;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public Integer getTotalPrice() {return totalPrice;}public void setTotalPrice(Integer totalPrice) {this.totalPrice = totalPrice;}
}

Flowable任务处理类

  • CreateOderProcess
package com.zzq.process;import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class CreateOderProcess implements JavaDelegate {private static final Logger log = LoggerFactory.getLogger(CreateOderProcess.class);@Overridepublic void execute(DelegateExecution delegateExecution) {log.info("订单创建成功 {}",delegateExecution.getVariable("order"));}
}
  • SendMailProcess
package com.zzq.process;import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;public class SendMailProcess implements JavaDelegate {private static final Logger log = LoggerFactory.getLogger(SendMailProcess.class);@Overridepublic void execute(DelegateExecution delegateExecution) {log.info("发送审核邮件 {} ",delegateExecution.getVariable("order"));}
}

验证

启动程序

  • 配置了database-schema-update: true第一次启动会自动创建表
    在这里插入图片描述

在这里插入图片描述

调用接口

  • 创建采购订单, /orderFlow/create_order ,返回流程实例ID

    • 不需要经理确认
      在这里插入图片描述
    • 需要经理确认
      在这里插入图片描述
  • 查看待确认的订单,返回任务id拼接Order
    在这里插入图片描述

  • 查看某个流程处理进度显示,传入流程实例id
    在这里插入图片描述

  • 经理调用确认采购订单,传入taskId
    在这里插入图片描述

  • 确认后再调用待确认订单接口也就没有刚才的任务id了
    在这里插入图片描述

  • 验证完成

本文源码

  • https://github.com/1030907690/flowable-sample

参考

  • https://www.bilibili.com/video/BV1gnkJYJEbg/
  • https://blog.csdn.net/qq_34162294/article/details/143806673
  • https://blog.51cto.com/u_16213663/10188533
  • https://blog.csdn.net/houyj1986/article/details/85546680

文章转载自:
http://chieftainship.apjjykv.cn
http://banksman.apjjykv.cn
http://borough.apjjykv.cn
http://bromize.apjjykv.cn
http://advancement.apjjykv.cn
http://bilious.apjjykv.cn
http://aubergiste.apjjykv.cn
http://adullamite.apjjykv.cn
http://caird.apjjykv.cn
http://aok.apjjykv.cn
http://choreograph.apjjykv.cn
http://april.apjjykv.cn
http://advantageous.apjjykv.cn
http://benefaction.apjjykv.cn
http://caravansarai.apjjykv.cn
http://absorbate.apjjykv.cn
http://capreomycin.apjjykv.cn
http://brook.apjjykv.cn
http://beholden.apjjykv.cn
http://auew.apjjykv.cn
http://alundum.apjjykv.cn
http://barbados.apjjykv.cn
http://belock.apjjykv.cn
http://chairwoman.apjjykv.cn
http://acetabularia.apjjykv.cn
http://aeromancy.apjjykv.cn
http://artificially.apjjykv.cn
http://ashen.apjjykv.cn
http://alkaline.apjjykv.cn
http://adgb.apjjykv.cn
http://www.dtcms.com/a/277793.html

相关文章:

  • 谷歌在软件工程领域应用AI的进展与未来展望
  • v-for中key值的作用:为什么我总被要求加这个‘没用的‘属性?
  • Linux-网络管理
  • OneCode 3.0 权限引擎实现详解:基于esdright模块的设计与架构
  • 【micro:bit】从入门到放弃(一):在线、离线版本的使用
  • 代码部落 20250713 CSP-J复赛 模拟赛
  • 适配器模式:兼容不兼容接口
  • C++--unordered_set和unordered_map的使用
  • C#接口进阶:继承与多态实战解析
  • DVWA靶场通关笔记-XSS DOM(Medium级别)
  • 在人工智能自动化编程时代:AI驱动开发和传统软件开发的分析对比
  • 如何自动化处理TXT日志,提升工作效率新方式
  • Autotab:用“屏幕录制”训练AI助手,解锁企业级自动化新范式
  • Springboot实现一个接口加密
  • 免费证件照工具,一键制作超方便
  • Linux驱动开发2:字符设备驱动
  • NumPy实战指南:解锁科学计算的超能力
  • 5.适配器模式
  • Chrome浏览器此扩展程序已停用,因为它已不再受支持,插件被停用解决方案
  • 解决 Python 跨目录导入模块问题
  • Ubuntu 设置自动挂载 SD 卡,扩容根目录
  • 进程互斥的硬件实现方法
  • Python----大模型(Langchain-Prompt提示词)
  • 快速搭建Maven仓库服务
  • 大话数据结构之 <顺序表> (C语言)
  • 学习:JS基础[5]对象
  • 【SpringAI Alibaba】基于 Redis 实现连续对话与向量存储
  • VsCode的LivePreview插件应用
  • [Java恶补day41] 226. 翻转二叉树
  • 基于springboot的大学公文收发管理系统