引擎配置類介紹
ProcessEngineConfigUration
查找并解析xml配置文件activiti.cfrg.xml
提供多個靜態(tài)方法配置對象
實現(xiàn)幾個基于不通場景的子類靜態(tài)方法創(chuàng)建配置對象
- 默認路徑加載一個資源配置文件構(gòu)造對象:ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault()
- 指定目錄加載一個資源配置文件構(gòu)造對象
ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(String)- 指定目錄和修改id類型加載一個資源配置文件構(gòu)造對象
ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(String,String)- 通過流加載一個資源配置文件構(gòu)造對象
ProcessEngineConfiguration.createProcessEngineConfigurationFromInputStream(InputStream)- 通過流和修改id類型加載一個資源配置文件構(gòu)造對象
ProcessEngineConfiguration.createProcessEngineConfigurationFromInputStream(InputStream,String)- 獨立的引擎配置對象
ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration()- 通過內(nèi)存數(shù)據(jù)庫構(gòu)造對象
ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration()
- 流程引擎配置及子類
ProcessEngineConfiguration - ProcessEngineConfigurationImpl 抽象類配置了ProcessEngineConfiguration的戶型
- StandaloneProcessEngineConfiguration 通過new的方式創(chuàng)建對象
- SpringProcessEngineConfiguration 基于spring集成完成擴展
創(chuàng)建流程引擎配置-創(chuàng)建maven activiti腳手架
- 打開activiti6.0源碼 cd tooling/archetypes/
- mvn clean install
-
添加main/java 與main/resources 目錄
image.png -
把helloworld項目里面到main函數(shù)與配置文件復(fù)制過來,并修改archetype-metadata.xml
image.png -
修改main函數(shù)里面到參數(shù)
image.png
- cd activiti-archetype-unittest/
- mvn clean install
-
添加到maven腳手架
image.png
創(chuàng)建流程引擎配置 config_samples
創(chuàng)建新的項目并創(chuàng)建子模塊選擇自己創(chuàng)建的腳手架
測試其他引擎配置類
public class ConfigTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigTest.class);
@Test
public void testConfig1(){
//基于activiti.cfg.xml 并創(chuàng)建基于內(nèi)存的h2數(shù)據(jù)庫對象依賴spring容器創(chuàng)建
ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault();
logger.info("configuration = {}",cfg);
}
@Test
public void testConfig2(){
//獨立的引擎配置對象
ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
logger.info("configuration = {}",cfg);
}
}
流程引擎數(shù)據(jù)庫配置
- 缺省默認配置,使用H2內(nèi)存數(shù)據(jù)庫
- 配置jdbc屬性,使用mybatis鏈接池
- 配置DataSource,可自選第三方實現(xiàn)
配置jdbc屬性,使用mybatis鏈接池
基本配置
jdbcUrl、jdbcDriver、jdbcUsername、jdbcPassword
鏈接池配置
jdbcMaxActiveConnections、jdbcMaxIdleConnections、jdbcMaxCheckoutTime、jdbcMaxWaitTime
配置DataSource,可自選第三方實現(xiàn)
- Druid 為監(jiān)控而生的數(shù)據(jù)庫鏈接池來自阿里
- Dbcp 老牌數(shù)據(jù)源鏈接池,穩(wěn)定可靠,Tomcat自帶
- HikarIcp 來自日本的極速數(shù)據(jù)源鏈接池,spring默選
Druid鏈接池activiti.cfg.xml配置
數(shù)據(jù)庫更新策略
配置DatabaseSchemaUpdate
- false:啟動時檢查數(shù)據(jù)庫版本,發(fā)生不匹配拋異常,適用于生產(chǎn)環(huán)境
- true:啟動時自動檢查并更新數(shù)據(jù)庫表,不存在創(chuàng)建,適用與開發(fā)環(huán)境
- create-drop:啟動時創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),結(jié)束時刪除表結(jié)構(gòu),適用于測試環(huán)境
引擎配置數(shù)據(jù)庫Demo
通過修改 activiti.cfg.xml 把默認的H2數(shù)據(jù)庫改成mysql數(shù)據(jù)庫
創(chuàng)建測試類
public class ConfigDBTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigDBTest.class);
@Test
public void testConfig1(){
ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResourceDefault();
logger.info("configuration = {}",cfg);
ProcessEngine processEngine = cfg.buildProcessEngine();
logger.info("獲取流程引擎 {}",processEngine.getName());
processEngine.close();
}
}
修改 activiti.cfg.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
</bean>
</beans>
通過修改創(chuàng)建新的配置文件并指定把鏈接方式改成druid鏈接
創(chuàng)建一個新的配置文件
activiti_druid.cfg.xml文件內(nèi)容
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--數(shù)據(jù)源-->
<property name="dataSource" ref="dataSource"/>
<!--是否需要歷史數(shù)據(jù)-->
<property name="dbHistoryUsed" value="true"/>
<!--是否需要用戶數(shù)據(jù)-->
<property name="dbIdentityUsed" value="true"/>
<!--給表加前綴-->
<property name="databaseTablePrefix" value="T_"/>-
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="2"/>
<property name="maxActive" value="10"/>
</bean>
</beans>
讀取配置文件
public class ConfigDBTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigDBTest.class);
@Test
public void testConfig2(){
ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti_druid.cfg.xml");
logger.info("configuration = {}",cfg);
ProcessEngine processEngine = cfg.buildProcessEngine();
logger.info("獲取流程引擎 {}",processEngine.getName());
processEngine.close();
}
}
日志記錄配置開啟mdc日志記錄
加 LogMDC.setMDCEnabled(true);當出現(xiàn)異常時會在日志顯示流程id等信息
public class ConfigMDCTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigMDCTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_mdc.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
LogMDC.setMDCEnabled(true);
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
assertNotNull(processInstance);
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
assertEquals("Activiti is awesome!", task.getName());
activitiRule.getTaskService().complete(task.getId());
}
}
通過攔截器設(shè)置MDC
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--自定義攔截每次執(zhí)行流程都打印流程id-->
<property name="commandInvoker" ref="commandInvoker"/>
</bean>
<bean id="commandInvoker" class="com.guosh.activiti.interceptor.MDCCommandInvoker"/>
</beans>
public class MDCCommandInvoker extends DebugCommandInvoker {
private static final Logger logger = LoggerFactory.getLogger(DebugCommandInvoker.class);
@Override
public void executeOperation(Runnable runnable) {
boolean mdcEnabled = LogMDC.isMDCEnabled();
LogMDC.setMDCEnabled(true);
if (runnable instanceof AbstractOperation) {
AbstractOperation operation = (AbstractOperation) runnable;
if (operation.getExecution() != null) {
LogMDC.putMDCExecution(operation.getExecution());
}
}
super.executeOperation(runnable);
LogMDC.clear();
if(!mdcEnabled){
LogMDC.setMDCEnabled(false);
}
}
}
歷史記錄配置
配置HistoryLevel(流程結(jié)束后的歷史記錄)
- none:不記錄歷史流程,性能高,流程結(jié)束后不可讀取
- activiti:歸檔流程實例,流程變量不同步(能看到歷史內(nèi)容歷史活動)
- audit:默認值,在activiti基礎(chǔ)上同步變量值,保存表單屬性(能看到歷史表單,歷史詳情)
- full:性能較差,記錄所有實例和變量細節(jié)變化(上面基礎(chǔ)上能看到詳情的變化)
測試文件
public class ConfigMDCTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigMDCTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_history.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
//啟動流程
startProcessInstance();
//修改變量
changeVariable();
//提交表單task
submitTaskForm();
//輸出歷史內(nèi)容
//輸出歷史活動
showHistoryActivity();
//歷史變量
showHistoryVaiable();
//輸出歷史用戶任務(wù)
showHistoryTask();
//歷史表單詳情
showHistoryForm();
//輸出歷史詳情
showHistoryDetail();
}
private void showHistoryDetail() {
List<HistoricDetail> historicDetails = activitiRule.getHistoryService().createHistoricDetailQuery().list();
for (HistoricDetail historicDetail:historicDetails) {
logger.info("historicDetail = {}",historicDetail);
}
logger.info("historicDetails.size = {}",historicDetails.size());
}
private void showHistoryForm() {
List<HistoricDetail> historicDetailsFrom = activitiRule.getHistoryService().createHistoricDetailQuery().formProperties().list();
for (HistoricDetail historicDetail:historicDetailsFrom) {
logger.info("historicDetail = {}",historicDetail);
}
logger.info("historicDetailsFrom.size = {}",historicDetailsFrom.size());
}
private void showHistoryTask() {
List<HistoricTaskInstance> historicTaskInstances = activitiRule.getHistoryService().createHistoricTaskInstanceQuery().list();
for (HistoricTaskInstance historicTaskInstance:historicTaskInstances) {
logger.info("historicTaskInstance = {}",historicTaskInstance);
}
logger.info("historicTaskInstances.size = {}",historicTaskInstances.size());
}
private void showHistoryVaiable() {
List<HistoricVariableInstance> historicVariableInstances = activitiRule.getHistoryService().createHistoricVariableInstanceQuery().list();
for (HistoricVariableInstance historicActivityInstance:historicVariableInstances) {
logger.info("historicActivityInstance = {}",historicActivityInstance);
}
logger.info("historicVariableInstances.size = {}",historicVariableInstances.size());
}
private void showHistoryActivity() {
List<HistoricActivityInstance> historicActivityInstances = activitiRule.getHistoryService().createHistoricActivityInstanceQuery().list();
for (HistoricActivityInstance historicActivityInstance:historicActivityInstances) {
logger.info("historicActivityInstance = {}",historicActivityInstance);
}
logger.info("historicActivityInstance.size = {}",historicActivityInstances.size());
}
private void submitTaskForm() {
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
Map<String,String> properties= Maps.newHashMap();
properties.put("formKey1","valuef1");
properties.put("formKey2","valuef2");
activitiRule.getFormService().submitTaskFormData(task.getId(),properties);
}
private void changeVariable() {
List<Execution> executions = activitiRule.getRuntimeService().createExecutionQuery().listPage(0, 100);
for (Execution execution:executions) {
logger.info("execution = {}",execution);
}
logger.info("execution.size = {}", executions.size());
String id=executions.iterator().next().getId();
activitiRule.getRuntimeService().setVariable(id,"keyStart1","value1_");
}
private void startProcessInstance() {
Map<String,Object> params= Maps.newHashMap();
params.put("keyStart1","value1");
params.put("keyStart2","value2");
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process",params);
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--自定義攔截每次執(zhí)行流程都打印流程id-->
<property name="commandInvoker" ref="commandInvoker"/>
<!--查看歷史的級別-->
<!--所有歷史都看不到-->
<!--<property name="history" value="none"/>-->
<!--能查看歷史活動歷史變量-->
<!--<property name="history" value="activity"/>-->
<!--能查看到所有,但是查看不到數(shù)據(jù)的修改記錄-->
<!--<property name="history" value="audit"/>-->
<property name="history" value="full"/>
</bean>
<bean id="commandInvoker" class="com.guosh.activiti.interceptor.MDCCommandInvoker"/>
</beans>
事件處理及監(jiān)聽器配置
事件處理
enableDatabaseEventLogging 作用監(jiān)聽變化記錄變化日志
public class ConfigEventLogTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigEventLogTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_evenlog.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
assertEquals("Activiti is awesome!", task.getName());
activitiRule.getTaskService().complete(task.getId());
//根據(jù)流程id查詢
List<EventLogEntry> envenLogEntrys = activitiRule.getManagementService()
.getEventLogEntriesByProcessInstanceId(processInstance.getId());
for (EventLogEntry eventLogEntry:envenLogEntrys) {
logger.info("eventLogEntry.type = {},eventLogEntry.data = {}",eventLogEntry.getType(),eventLogEntry.getData());
}
logger.info("envenLogEntrys.sice = {},eventLogEntry.data = {}",envenLogEntrys.size());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--自定義攔截每次執(zhí)行流程都打印流程id-->
<property name="commandInvoker" ref="commandInvoker"/>
<!--事件監(jiān)聽器-->
<property name="enableDatabaseEventLogging" value="true"/>
</bean>
<bean id="commandInvoker" class="com.guosh.activiti.interceptor.MDCCommandInvoker"/>
</beans>
監(jiān)聽器配置
- 配置Listener
- eventListeners: 監(jiān)聽所有事件派發(fā)通知
- typedEventListeners:監(jiān)聽指定事件類型的通知
- activiti:eventListener:只監(jiān)聽特定的流程定義事件
- 相關(guān)Api
- ActivitiEvent:事件對象
- ActivitiEventListener:監(jiān)聽器
- ActivitiEventType:事件類型
1.注冊監(jiān)聽第一種寫法
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--第一種方式-->
<property name="eventListeners">
<list>
<bean class="com.guosh.activiti.event.ProcessEventListener"/>
</list>
</property>
</beans>
public class ProcessEventListener implements ActivitiEventListener {
private static final Logger logger= LoggerFactory.getLogger(ProcessEventListener.class);
@Override
public void onEvent(ActivitiEvent event) {
ActivitiEventType eventType = event.getType();
//判斷如果是流程啟動
if(ActivitiEventType.PROCESS_STARTED.equals(eventType)){
logger.info("流程啟動 {} \t {}",event.getType(),event.getProcessInstanceId());
}
//流程結(jié)束
else if(ActivitiEventType.PROCESS_COMPLETED.equals(eventType)){
logger.info("流程結(jié)束 {} \t {}",event.getType(),event.getProcessInstanceId());
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
2.注冊監(jiān)聽第二種寫法
<property name="typedEventListeners">
<map>
<!--流程啟動-->
<entry key="PROCESS_STARTED">
<list>
<bean class="com.guosh.activiti.event.ProcessEventListener"/>
</list>
</entry>
</map>
</property>
3.自定義監(jiān)聽
public class ConfigEventListenerTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigEventListenerTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_evenlistener.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
assertEquals("Activiti is awesome!", task.getName());
activitiRule.getTaskService().complete(task.getId());
//發(fā)出一個自定義事件
activitiRule.getRuntimeService().dispatchEvent(new ActivitiActivityEventImpl(ActivitiEventType.CUSTOM));
}
}
public class CustomEventListener implements ActivitiEventListener {
private static final Logger logger= LoggerFactory.getLogger(CustomEventListener.class);
@Override
public void onEvent(ActivitiEvent event) {
ActivitiEventType eventType = event.getType();
//判斷如果是自定義的事件
if(ActivitiEventType.CUSTOM.equals(eventType)){
logger.info("監(jiān)聽到自定義事件 {} \t {}",event.getType(),event.getProcessInstanceId());
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--自定義監(jiān)聽事件-->
<property name="eventListeners">
<list>
<bean class="com.guosh.activiti.event.CustomEventListener"/>
</list>
</property>
</bean>
<bean id="commandInvoker" class="com.guosh.activiti.interceptor.MDCCommandInvoker"/>
</beans>
4.通過代碼注冊監(jiān)聽
public class ConfigEventListenerTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigEventListenerTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_evenlistener.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
activitiRule.getRuntimeService().addEventListener(new CustomEventListener());
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
assertEquals("Activiti is awesome!", task.getName());
activitiRule.getTaskService().complete(task.getId());
//通過addEventListener注冊
activitiRule.getRuntimeService().addEventListener(new CustomEventListener());
//發(fā)出一個自定義事件
activitiRule.getRuntimeService().dispatchEvent(new ActivitiActivityEventImpl(ActivitiEventType.CUSTOM));
}
}
命令攔截器的配置
-
命令模式與責任鏈模式
image.png
- 攔截器的配置方式
配置Interceptor
- customPreCommandInterceptors:配置在默認攔截器之前
- customPostCommandInterceptors:配置在默認攔截器之后
- commandInvoker:配置最后的執(zhí)行器
public class DurationCommandInterceptor extends AbstractCommandInterceptor {
private static final Logger logger = LoggerFactory.getLogger(DurationCommandInterceptor.class);
@Override
public <T> T execute(CommandConfig config, Command<T> command) {
//取毫秒數(shù)
long start =System.currentTimeMillis();
try {
return this.getNext().execute(config,command);
}finally {
long duration = System.currentTimeMillis() - start;
logger.info("{} 執(zhí)行時長 {} 毫秒",command.getClass().getSimpleName(),duration);
}
}
}
public class ConfigInterceptorTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigInterceptorTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_interceptor.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process.bpmn20.xml"})
public void test() {
ProcessInstance processInstance = activitiRule.getRuntimeService().startProcessInstanceByKey("my-process");
Task task = activitiRule.getTaskService().createTaskQuery().singleResult();
assertEquals("Activiti is awesome!", task.getName());
activitiRule.getTaskService().complete(task.getId());
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--攔截器-->
<property name="customPreCommandInterceptors">
<list>
<bean class="com.guosh.activiti.interceptor.DurationCommandInterceptor"/>
</list>
</property>
<property name="customPostCommandInterceptors">
<list>
<bean class="com.guosh.activiti.interceptor.DurationCommandInterceptor"/>
</list>
</property>
<!--能實現(xiàn)mdc同樣的效果-->
<property name="enableVerboseExecutionTreeLogging" value="true"/>
<!--自定義攔截每次執(zhí)行流程都打印流程id-->
<!-- <property name="commandInvoker" ref="commandInvoker"/>-->
</bean>
<bean id="commandInvoker" class="com.guosh.activiti.interceptor.MDCCommandInvoker"/>
</beans>
作業(yè)執(zhí)行器
- 作業(yè)執(zhí)行器的配置
相關(guān)配置
- asyncExecutorActivate:激活作業(yè)執(zhí)行器
- asyncExecutorXXX:異步執(zhí)行器對屬性配置
- asyncExecutor:異步執(zhí)行期bean
定時開始事件
timDate:指定啟動時間
timeDuration:指定持續(xù)時間間隔后執(zhí)行
timCycle:R5/P1DT1H指定事件段后周期執(zhí)行
- 配置自定義線程池
自定義線程池ExecutorService - threadNamePrefix:線程池名字前綴
- corePoolSice:核心線程數(shù)
- maxPoolSize:最大線程數(shù)
- queueCapacity:堵塞隊列大小
- 流程定義定時啟動流程
線程池配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false" />
<property name="jdbcDriver" value="com.mysql.jdbc.Driver" />
<property name="jdbcUsername" value="root" />
<property name="jdbcPassword" value="root" />
<!--數(shù)據(jù)庫更新策略-->
<property name="databaseSchemaUpdate" value="true"/>
<!--異步激活器-->
<property name="asyncExecutorActivate" value="true"/>
<!--異步執(zhí)行器-->
<property name="asyncExecutor" ref="asyncExecutor"/>
<!--監(jiān)聽JOB事件-->
<property name="eventListeners">
<list>
<bean class="com.guosh.activiti.event.JobEventListener"/>
</list>
</property>
</bean>
<bean id="asyncExecutor" class="org.activiti.engine.impl.asyncexecutor.DefaultAsyncJobExecutor">
<property name="executorService" ref="executorService"/>
</bean>
<!--線程池-->
<bean id="executorService" class="org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean">
<!--線程池名字前綴-->
<property name="threadNamePrefix" value="activiti-job"/>
<!--核心線程池-->
<property name="corePoolSize" value="5"/>
<!--最大線程數(shù)-->
<property name="maxPoolSize" value="20"/>
<!--堵塞隊列大小-->
<property name="queueCapacity" value="100"/>
<!--拒絕策略-->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$AbortPolicy"/>
</property>
</bean>
</beans>
流程定時任務(wù)配置
<?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: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" typeLanguage="http://www.w3.org/2001/XMLSchema"
expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
<process id="my-process">
<!--<startEvent id="start" />-->
<startEvent id="start" >
<!--定時啟動-->
<timerEventDefinition>
<!--含義執(zhí)行五次間隔十秒-->
<timeCycle>R5/PT10S</timeCycle>
</timerEventDefinition>
</startEvent>
<sequenceFlow id="flow1" sourceRef="start" targetRef="someTask" />
<userTask id="someTask" name="Activiti is awesome!" />
<sequenceFlow id="flow2" sourceRef="someTask" targetRef="end" />
<endEvent id="end" />
</process>
</definitions>
定時任務(wù)事件監(jiān)聽
public class JobEventListener implements ActivitiEventListener {
private static final Logger logger= LoggerFactory.getLogger(JobEventListener.class);
@Override
public void onEvent(ActivitiEvent event) {
ActivitiEventType eventType = event.getType();
String name=eventType.name();
//判斷如果是自定義的事件
if(name.startsWith("TIMER")||name.startsWith("JOB")){
logger.info("監(jiān)聽到JOB事件 {} \t {}",event.getType(),event.getProcessInstanceId());
}
}
@Override
public boolean isFailOnException() {
return false;
}
}
public class ConfigJobTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigJobTest.class);
@Rule
public ActivitiRule activitiRule = new ActivitiRule("activiti_job.cfg.xml");
@Test
@Deployment(resources = {"com/guosh/activiti/my-process_job.bpmn20.xml"})
public void test() throws InterruptedException {
logger.info("start");
//當前有多少個定時任務(wù)在執(zhí)行
List<Job> jobs = activitiRule.getManagementService().createTimerJobQuery().list();
for (Job job:jobs) {
logger.info("定時任務(wù) = {},默認重試次數(shù) = {}",job,job.getRetries());
}
logger.info("jobs.size = {}", jobs.size());
//等待
Thread.sleep(1000*100);
logger.info("end");
}
}
集成Spring配置
相關(guān)配置
- 添加pom依賴activiti-spring
- 基于spring的默認配置activiti-context.xml
- Activiti核心服務(wù)注入Spring容器
功能特征
- 集成spring事物管理器
- 定義文件表達式中使用Spring bean
- 自動部署資源文件
單元測試
- 添加pom依賴spring-test
- 輔助測試Rule:ActivitiRule
- 輔助測試TestCase:SpringActrivitiTest
配置activiti-context.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
<property name="databaseSchemaUpdate" value="true"/>
<!--數(shù)據(jù)源-->
<property name="dataSource" ref="dataSource"/>
<!--事務(wù)管理器-->
<property name="transactionManager" ref="transactionManager"/>
</bean>
<!--流程引擎對象-->
<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration"/>
</bean>
<!--注冊服務(wù)-->
<bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
<bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
<bean id="formService" factory-bean="processEngine" factory-method="getFormService"/>
<bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
<bean id="activitiRule" class="org.activiti.engine.test.ActivitiRule">
<property name="processEngine" ref="processEngine"/>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="jdbc:mysql://127.0.0.1:3306/activiti6unit?useUnicode=true&characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="2"/>
<property name="maxActive" value="10"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="helloBean" class="com.guosh.activiti.delegate.HelloBean"></bean>
</beans>
測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:activiti-context.xml"})
public class ConfigSpringTest {
private static final Logger logger= LoggerFactory.getLogger(ConfigSpringTest.class);
@Rule
@Autowired
public ActivitiRule activitiRule;
@Autowired
private RuntimeService runtimeService;
@Autowired
private TaskService taskService;
@Test
@Deployment(resources = {"com/guosh/activiti/my-process_spring.bpmn20.xml"})
public void test() {
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("my-process");
assertNotNull(processInstance);
Task task = taskService.createTaskQuery().singleResult();
taskService.complete(task.getId());
}
}
my-process_spring.bpmn20.xml流程文件
<?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: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" typeLanguage="http://www.w3.org/2001/XMLSchema"
expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/test">
<process id="my-process">
<startEvent id="start" />
<sequenceFlow id="flow1" sourceRef="start" targetRef="someTask" />
<userTask id="someTask" name="Activiti is awesome!" />
<sequenceFlow id="flow2" sourceRef="someTask" targetRef="helloBean" />
<!--${helloBean.sayHello()}可以調(diào)取到自己寫到類到方法-->
<serviceTask id="helloBean" activiti:expression="${helloBean.sayHello()}"/>
<sequenceFlow id="flow3" sourceRef="helloBean" targetRef="end" />
<endEvent id="end" />
</process>
</definitions>