Activiti工作流引擎

Activiti是什么

  • Activiti项目是一项新的基于Apache许可的开源BPM平台,从基础开始构建,旨在提供支持新的BPMN 2.0标准。
  • Activiti是一种轻量级,可嵌入的BPM引擎,而且还设计适用于可扩展的云架构。 Activiti将提供宽松的Apache许可2.0,同时促进Activiti BPM引擎和BPMN 2.0的匹配。

使用工作流引擎的好处

工作流引擎最常见用于审批流程中,现在一线互联网公司也开始使用,并有快速推广的趋势,复杂繁多的业务流程如果采用if else实现那将是崩溃的,代码不可维护,业务流程在代码中可读性很差,所以高人设计了业务流程模型图示BPMN2.0,我们要做到就是把业务场景抽象为标准流程图,把流程图丢到流程引擎中按流程定义约定逐步流转,很显然扩展性和业务可描述性会好很多,所以工作流引擎主要用于解决复杂的业务,目前经常被提起的中台系统抽象业务为服务,也涉及大量智能的业务流程引擎做支撑。

如何快速上手

1.1 搭建流程引擎

我们在IDEA环境中使用 Spring Initializr引导我们创建一个标准工程,采用最新稳定版spring boot 2.0.2,Activiti 6.0,通过引入H2内存数据库,当程序启动Spring boot会基于自动配置原理给我们隐式的创建一个工作流引擎对象ProcessEngine,并把RuntimeService(控制流程运行时数据流转)等核心服务注册到 Spring 容器中,我们只需要 依赖注入使用即可。

1.2 开发

pom.xml如下所示:

// pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.imooc.activiti</groupId>
    <artifactId>activiti-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>activiti-demo</name>
    <description>Demo project for Spring Boot</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>24.0-jre</version>
        </dependency>
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-spring-boot-starter-basic</artifactId>
            <version>6.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
1.3 设计流程定义文件

在这里插入图片描述
流程定义文件xml如下:

// src/main/resources/processes/second_approve.bpmn

<?xml version="1.0" encoding="UTF-8"?><definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" xmlns:tns="http://www.activiti.org/test" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test" id="m1528728906382" name="">
  <process id="second_approve" name="二级审批流程" isExecutable="true" isClosed="false" processType="None">
    <startEvent id="startEvent" name="开始"></startEvent>
    <userTask id="submitForm" name="填写审批信息">
      <extensionElements>
        <activiti:formProperty id="message" name="申请信息" type="string" required="true"></activiti:formProperty>
        <activiti:formProperty id="name" name="申请人姓名" type="string" required="true"></activiti:formProperty>
        <activiti:formProperty id="submitTime" name="提交时间" type="date" datePattern="yyyy-MM-dd" required="true"></activiti:formProperty>
        <activiti:formProperty id="submitType" name="确认申请" type="string" required="true"></activiti:formProperty>
      </extensionElements>
    </userTask>
    <sequenceFlow id="flow1" sourceRef="startEvent" targetRef="submitForm"></sequenceFlow>
    <exclusiveGateway id="decideSubmit" name="提交OR取消"></exclusiveGateway>
    <sequenceFlow id="flow2" sourceRef="submitForm" targetRef="decideSubmit"></sequenceFlow>
    <userTask id="tl_approve" name="主管审批">
      <extensionElements>
        <activiti:formProperty id="tlApprove" name="主管审批结果" type="string"></activiti:formProperty>
        <activiti:formProperty id="tlMessage" name="主管备注" type="string" required="true"></activiti:formProperty>
      </extensionElements>
    </userTask>
    <sequenceFlow id="flow3" sourceRef="decideSubmit" targetRef="tl_approve">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[${submitType == "y" || submitType == "Y"}]]></conditionExpression>
    </sequenceFlow>
    <exclusiveGateway id="decideTLApprove" name="主管审批校验"></exclusiveGateway>
    <sequenceFlow id="flow4" sourceRef="tl_approve" targetRef="decideTLApprove"></sequenceFlow>
    <endEvent id="endEvent" name="结束"></endEvent>
    <endEvent id="endEventCancel" name="取消"></endEvent>
    <sequenceFlow id="flow8" sourceRef="decideSubmit" targetRef="endEventCancel">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[${submitType == "n" || submitType == "N"}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="flow9" sourceRef="decideTLApprove" targetRef="submitForm">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[${tlApprove == "n" || tlApprove == "N"}]]></conditionExpression>
    </sequenceFlow>
    <sequenceFlow id="_2" sourceRef="decideTLApprove" targetRef="endEvent">
      <conditionExpression xsi:type="tFormalExpression"><![CDATA[${tlApprove == "y" || tlApprove == "Y"}]]></conditionExpression>
    </sequenceFlow>
  </process>
 </definitions>

流程执行我们使用了CommandLineRunner,这个类的事例会在Spring boot容器启动加载完成后直接运行

@Configuration
@Slf4jpublic class AutoConfigurationProcessDemo {
    @Autowired    private RuntimeService runtimeService;
    @Autowired    private TaskService taskService;
    @Autowired    private FormService formService;   
     /**
     * 命令行执行
     *
     * @return
     */
    @Bean  
    public CommandLineRunner commandLineRunner() {        
        return new CommandLineRunner() {
            @Override            
            public void run(String... args) throws Exception {                
                log.info("启动我们的程序");                
                //启动运行流程
                ProcessInstance processInstance = startProcessInstance("second_approve");                
                //处理流程任务
                processTask(processInstance);                
                log.info("结束我们的程序");
            }
        };
    }    /**
     * 处理流程任务
     *
     * @param processInstance
     * @throws ParseException
     */
    private void processTask(ProcessInstance processInstance) throws ParseException {
        Scanner scanner = new Scanner(System.in);        
        while (processInstance != null && !processInstance.isEnded()) {
            List<Task> list = taskService.createTaskQuery().list();            
            log.info("待处理任务数量 [{}]", list.size());            
            for (Task task : list) {                
            log.info("待处理任务 [{}]", task.getName());
                Map<String, Object> variables = buildVariablesByScanner(scanner, task);
                taskService.complete(task.getId(), variables);
                processInstance = runtimeService
                        .createProcessInstanceQuery()
                        .processInstanceId(processInstance.getId())
                        .singleResult();
            }
        }
        scanner.close();
    }    /**
     * 从控制台获取变量
     *
     * @param scanner
     * @param task
     * @return
     * @throws ParseException
     */
    private Map<String, Object> buildVariablesByScanner(Scanner scanner, Task task) throws ParseException {
        TaskFormData taskFormData = formService.getTaskFormData(task.getId());
        List<FormProperty> formProperties = taskFormData.getFormProperties();        
        return buildVariablesByScanner(scanner, formProperties);
    }    
    
    public static Map<String, Object> buildVariablesByScanner(Scanner scanner, List<FormProperty> formProperties) throws ParseException {
        Map<String, Object> variables = Maps.newHashMap();        
        for (FormProperty property : formProperties) {            
        String line = null;            
        if (StringFormType.class.isInstance(property.getType())) {                
        log.info("请输入 {} ?", property.getName());                
        line = scanner.nextLine();
                variables.put(property.getId(), line);
            } else if (DateFormType.class.isInstance(property.getType())) {                
            log.info("请输入 {} ? 格式 (yyyy-MM-dd)", property.getName());               
            line = scanner.nextLine();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = dateFormat.parse(line);
                variables.put(property.getId(), date);
            } else {                
                log.info("类型暂不支持 {}", property.getType());
            }            
            log.info("您输入的内容是 [{}]", line);

        }        
        return variables;
    }    /**
     * 获取流程实例
     *
     * @param processDefinitionId
     * @return
     */
    private ProcessInstance startProcessInstance(String processDefinitionId) {
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionId);        log.info("启动流程 [{}]", processInstance.getProcessDefinitionKey());        return processInstance;
    }

}


为了让控制台输出更清晰直观,让控制台日志仅仅输出message日志信息,忽略默认格式中日志级别时间信息等等。

//src/main/resources/application.yml
logging:  
    pattern:    
        console: "%m%n"

结语

我对activiti也是刚接触的小白。如有不正确之处,请不吝赐教。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值