Nepxion Coroutine — это агрегационный фреймворк для распределённых вызовов на основе корутин, который разработан с использованием Kilim + Promise JDeferred + Zookeeper + Spring Boot. Он предоставляет возможности для хранения и динамического уведомления об агрегационных правилах.
Введение:
Фреймворк Nepxion Coroutine предлагает следующие возможности:
<?xml version="1.0" encoding="UTF-8"?>
<coroutine>
<!-- 规则定义 -->
<!-- 1. 规则目录 — это каталог (category) узла регистрации, а правило — имя узла, которое хранит текущее содержимое правила; если это локальное правило, эти два элемента могут быть определены произвольно. Например, при вызове метода CoroutineManager.load().startSync("Каталог правил", "Имя правила"...). -->
<!-- 2. В узле корутины может быть несколько узлов правил, которые различаются по номеру версии; процесс запуска использует правило с максимальным номером версии, и номер версии должен быть уникальным во всём мире. -->
<rule version="1">
<!-- Определение компонента правила -->
<!-- Компонент правила поддерживает локальные ссылки и удалённые распределённые ссылки (например, интерфейс Dubbo). -->
<!-- 1. Способ локальной ссылки на компонент правила, использующий механизм отражения класса. -->
<!-- class — определение класса, атрибут class — полный путь класса, например, class="com.nepxion.coroutine.test.service.impl.AServiceImpl". -->
<!-- index — уникальный номер индекса в текущем правиле. -->
<!-- method — определение метода, атрибут method — соответствующее имя метода. -->
<!-- parameterTypes — определение типа параметра, если в интерфейсе/классе существует полиморфный метод (то есть имя метода одинаково, но типы параметров различны), необходимо различать по типу параметра. -->
<component>
<class class="com.nepxion.coroutine.test.service.impl.AServiceImpl">
<method index="1" method="doA" parameterTypes="java.lang.String,int"/>
<method index="2" method="doA" parameterTypes="java.lang.String"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.BServiceImpl">
<method index="3" method="doB"/>
</class>
</component>
<!-- 2. Метод удалённого распределённого внедрения компонентов правил, использующий режим внедрения интерфейса. -->
<!-- applicationContext — стандартный контекст приложения Spring. -->
В запросе присутствуют только фрагменты кода, не несущие смысловой нагрузки. Для получения полной информации о проекте рекомендуется обратиться к исходному коду на GitHub. **Конфигурация путей XML, например:**
applicationContext="classpath*:cApplicationContext.xml", applicationContext.xml имя должно быть уникальным во всём мире -->
<!-- id для идентификатора Spring Bean, который должен быть уникальным во всем мире -->
<!-- index в качестве номера индекса, должен быть уникальным в соответствии с текущим правилом -->
<!-- method для определения метода, атрибут method соответствует имени метода -->
<!-- parameterTypes для определения типов параметров, если существует полиморфный метод (то есть методы с одинаковыми именами, но разными типами параметров) в интерфейсе/классе, необходимо использовать типы параметров для различения -->
<component applicationContext="classpath*:cApplicationContext.xml">
<class id="cService">
<method index="4" method="doC"/>
</class>
</component>
<component applicationContext="classpath*:dApplicationContext.xml">
<class id="dService">
<method index="5" method="doD"/>
</class>
</component>
<!-- Определение зависимостей дочерних правил, может существовать несколько узлов зависимостей -->
<!-- 1. Дочерние правила не могут ссылаться на текущие родительские правила, иначе это вызовет бесконечный цикл. Например, родительское правило A ссылается на дочернее правило B, а дочернее правило B снова ссылается на родительское правило A -->
<dependency index="5" category="A правила каталога" rule="A-1 правило" chain="a" timeout="5000"/>
<dependency index="6" category="A правила каталога" rule="A-2 правило" chain="b" timeout="5000"/>
<dependency index="7" category="B правила каталога" rule="B-1 правило" chain="c" timeout="5000"/>
<dependency index="8" category="B правила каталога" rule="B-2 правило" chain="d" timeout="5000"/>
<!-- Определение цепочки вызовов -->
<!-- Можно определить несколько цепочек. На стороне вызова необходимо передать значение name, если в конфигурации значение name не задано, можно передать null -->
<!-- 1. Список значений индекса (index) для параллельного выполнения (when), не требуется различать порядок -->
<!-- 2. Список значений индекса (index) для последовательного выполнения (then), требуется различать порядок -->
<chain name="x">
<then index="1,2"/>
<when index="3,4"/>
<then index="5,6,7,8"/>
</chain>
<chain name="y">
<then index="1,2"/>
<when index="3,4"/>
<then index="5,6,7,8"/>
</chain>
</rule>
</coroutine>
Асинхронный вызов
CoroutineManager.load().startAsync("PayRoute", "Rule", chainName, new String[] { "входящий параметр" }, false, new CoroutineCallback<CoroutineResult<Object>>() {
@Override
public void onResult(CoroutineResult<Object> result) {
LOG.info("Результат асинхронного обратного вызова: номер программы линии={}, идентификатор={}, результат={}", индекс, результат.getId(), результат.getResult());
}
@Override
public void onError(Exception exception) {
LOG.error("Исключение асинхронного обратного вызова", исключение);
}
});
Синхронный вызов
try {
CoroutineResult<Object> результат = CoroutineManager.load().startSync("PayRoute", "Rule", chainName, новый String[] { "входящий параметр" }, 3000, false);
LOG.info("Результат синхронного вызова: номер программы линии={}, идентификатор={}, результат={}", индекс, результат.getId(), результат.getResult());
} catch (Exception e) {
LOG.error("Синхронное исключение вызова", e);
}
См. проект coroutine-test
Определение правила 1
<?xml version="1.0" encoding="UTF-8"?>
<coroutine>
<rule version="1">
<component>
<class class="com.nepxion.coroutine.test.service.impl.AServiceImpl">
<method index="1" method="doThen"/>
<method index="2" method="doWhen"/>
<method index="3" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.BServiceImpl">
<method index="4" method="doThen"/>
<method index="5" method="doWhen"/>
<method index="6" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.CServiceImpl">
<method index="7" method="doThen"/>
<method index="8" method="doWhen"/>
<method index="9" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.DServiceImpl">
<method index="10" method="doThen"/>
<method index="11" method="doWhen"/>
<method index="12" method="doMerge"/>
</class>
</component>
<dependency index="13" category="PayRoute" rule="SubRule" chain="chain2-2" file="rule2.xml" timeout="5000"/>
<chain name="chain1-1">
<then index="1,4"/>
<when index="8,11"/>
<then index="12,1,13"/>
</chain>
<chain name="chain1-2">
<then index="1,4"/>
<when index="8,11"/>
<then index="12,1,13"/>
</chain>
</rule> **Определение правила 2**
```xml
<?xml version="1.0" encoding="UTF-8"?>
<coroutine>
<rule version="1">
<component>
<class class="com.nepxion.coroutine.test.service.impl.AServiceImpl">
<method index="1" method="doThen"/>
<method index="2" method="doWhen"/>
<method index="3" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.BServiceImpl">
<method index="4" method="doThen"/>
<method index="5" method="doWhen"/>
<method index="6" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.CServiceImpl">
<method index="7" method="doThen"/>
<method index="8" method="doWhen"/>
<method index="9" method="doMerge"/>
</class>
<class class="com.nepxion.coroutine.test.service.impl.DServiceImpl">
<method index="10" method="doThen"/>
<method index="11" method="doWhen"/>
<method index="12" method="doMerge"/>
</class>
</component>
<chain name="chain2-1">
<when index="2,5"/>
<then index="9,10"/>
<when index="8,11"/>
<then index="3,4"/>
</chain>
<chain name="chain2-2">
<then index="1,4,7,10"/>
</chain>
</rule>
</coroutine>
Вызов входа
package com.nepxion.coroutine.test;
/**
* <p>Title: Nepxion Coroutine</p>
* <p>Description: Nepxion Coroutine For Distribution</p>
* <p>Copyright: Copyright (c) 2017</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
import java.util.Timer;
import java.util.TimerTask;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nepxion.coroutine.common.callback.CoroutineCallback;
import com.nepxion.coroutine.data.entity.CoroutineResult;
import com.nepxion.coroutine.framework.core.CoroutineManager;
public class CoroutineTest {
private static final Logger LOG = LoggerFactory.getLogger(CoroutineTest.class);
@Test
public void testRemote() throws Exception {
// 请确保Zookeeper有对应的规则(运行CoroutineRuleRegistryTest相关方法)
// 从远程注册中心装载
// 启动和远程注册中心连接
CoroutineManager.start();
// 解析远端规则(支持子规则引用)
CoroutineManager.parseRemote("PayRoute", "Rule");
// 链名称从xml配置中获取
invokeAsync("chain1-1");
invokeSync("chain1-2");
System.in.read();
}
@Test
public void testLocalRule1() throws Exception {
// 从本地装载
// 解析本地规则(不支持子规则引用)
CoroutineManager.parseLocal("PayRoute", "Rule", "rule1.xml");
// 链名称从xml配置中获取
invokeAsync("chain1-1");
invokeSync("code1-2");
System.in.read();
}
@Test
public void testLocalRule2() throws Exception {
// 从本地装载
// 解析本地规则(不支持子规则引用)
CoroutineManager.parseLocal("PayRoute", "Rule", "rule2.xml");
// 链名称从xml配置中获取
invokeAsync("chain2-1");
invokeSync("chain2-2");
System.in.read();
}
public void invokeAsync(final String chainName) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
for (int i = 0; i < 1; i++) {
final int index = i % 5;
CoroutineManager.load().startAsync("PayRoute", "Rule", chainName, new String[] { "Start[" + index + "]" }, false, new CoroutineCallback<CoroutineResult<Object>>() {
@Override
public void onResult(CoroutineResult<Object> result) {
LOG.info("异步回调结果: 线程序号={}, id={}, result={}", index, result.getId(), result.getResult());
}
@Override
public void onError(Exception exception) {
LOG.error("异步回调异常", exception);
}
});
}
}
});
}
``` Данный фрагмент написан на языке Java.
public class CoroutineCache { public static void main(String[] args) { LOG.info("2017-12-23 19:13:43.641"); LOG.info("[Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.data.cache.CoroutineCache:39] - Daemon thread for scanning cache starts..."); LOG.info("2017-12-23 19:13:43.656"); LOG.info("[Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=1, categoryName=PayRoute, ruleName=Rule, chainName=chain1-2, class=com.nepxion.coroutine.test.service.impl.AServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=3 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375"); LOG.info("2017-12-23 19:13:43.656"); LOG.info("[Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=1, categoryName=PayRoute, ruleName=Rule, chainName=chain1-1, class=com.nepxion.coroutine.test.service.impl.AServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=3 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a"); LOG.info("2017-12-23 19:13:43.660"); LOG.info("[Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=4, categoryName=PayRoute, ruleName=Rule, chainName=chain1-2, class=com.nepxion.coroutine.test.service.impl.BServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375"); LOG.info("2017-12-23 19:13:43.660"); LOG.info("[Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=4, categoryName=PayRoute, ruleName=Rule, chainName=chain1-1, class=com.nepxion.coroutine.test.service.impl.BServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a"); LOG.info("2017-12-23 19:13:43.666"); LOG.info("[Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.common.thread.ThreadPoolFactory:38] - Thread pool executor is created, threadName=Promise-192.168.1.3-thread, corePoolSize=64, maximumPoolSize=128, keepAliveTime=900000, allowCoreThreadTimeOut=false"); LOG.info("2017-12-23 19:13:43.669"); LOG.info("[Promise-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=8, categoryName=PayRoute, ruleName=Rule, chainName=chain1-2, class=com.nepxion.coroutine.test.service.impl.CServiceImpl, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375"); LOG.info("2017-12-23 19:13:43.669"); LOG.info("[Promise-192.168.1.3-thread-2][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=11, categoryName=PayRoute, ruleName=Rule, chainName=chain1-2, class=com.nepxion.coroutine.test.service.impl.DServiceImpl, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375"); LOG.info(""); } }
* **Promise-192.168.1.3-thread-3**:
* referenceType = componentReference;
* index = 11;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-1;
* class = com.nepxion.coroutine.test.service.impl.DServiceImpl;
* method = doWhen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 98c84565-ca73-42b8-a2e8-da4dee6df22a.
* **Promise-192.168.1.3-thread-0**:
* referenceType = componentReference;
* index = 8;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-1;
* class = com.nepxion.coroutine.test.service.impl.CServiceImpl;
* method = doWhen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 98c84565-ca73-42b8-a2e8-da4dee6df22a.
* **Coroutine-192.168.1.3-thread-1**:
* referenceType = componentReference;
* index = 12;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-2;
* class = com.nepxion.coroutine.test.service.impl.DServiceImpl;
* method = doMerge;
* parameterTypes = com.nepxion.coroutine.data.entity.CoroutineList;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
* **Coroutine-192.168.1.3-thread-0**:
* referenceType = componentReference;
* index = 12;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-1;
* class = com.nepxion.coroutine.test.service.impl.DServiceImpl;
* method = doMerge;
* parameterTypes = com.nepxion.coroutine.data.entity.CoroutineList;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 98c84565-ca73-42b8-a2e8-da4dee6df22a.
* **Coroutine-192.168.1.3-thread-1**:
* referenceType = componentReference;
* index = 1;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-2;
* class = com.nepxion.coroutine.test.service.impl.AServiceImpl;
* method = doThen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
* **Coroutine-192.168.1.3-thread-0**:
* referenceType = componentReference;
* index = 1;
* categoryName = PayRoute;
* ruleName = Rule;
* chainName = chain1-1;
* class = com.nepxion.coroutine.test.service.impl.AServiceImpl;
* method = doThen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 98c84565-ca73-42b8-a2e8-da4dee6df22a.
* **Coroutine-192.168.1.3-thread-2**:
* referenceType = componentReference;
* index = 1;
* categoryName = PayRoute;
* ruleName = SubRule;
* chainName = chain2-2;
* class = com.nepxion.coroutine.test.service.impl.AServiceImpl;
* method = doThen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
* **Coroutine-192.168.1.3-thread-3**:
* referenceType = componentReference;
* index = 1;
* categoryName = PayRoute;
* ruleName = SubRule;
* chainName = chain2-2;
* class = com.nepxion.coroutine.test.service.impl.AServiceImpl;
* method = doThen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 98c84565-ca73-42b8-a2e8-da4dee6df22a.
* **Coroutine-192.168.1.3-thread-2**:
* referenceType = componentReference;
* index = 4;
* categoryName = PayRoute;
* ruleName = SubRule;
* chainName = chain2-2;
* class = com.nepxion.coroutine.test.service.impl.BServiceImpl;
* method = doThen;
* parameterTypes = java.lang.String;
* returnType = java.lang.String;
* spentTime = 0 ms;
* id = 6fcb1456-fc34-49a0-9ad4-832fd5f3f375. **Распределённый способ вызова на основе Spring**
2017-12-23 19:13:43.678 INFO [Coroutine-192.168.1.3-thread-2][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] — Сериализация завершена, referenceType=componentReference, index=4, categoryName=PayRoute, ruleName=SubRule, chainName=chain2-2, class=com.nepxion.coroutine.test.service.impl.BServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a.
2017-12-23 19:13:43.678 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] — Сериализация завершена, referenceType=componentReference, index=7, categoryName=PayRoute, ruleName=SubRule, chainName=chain2-2, class=com.nepxion.coroutine.test.service.impl.CServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
2017-12-23 19:13:43.678 INFO [Coroutine-192.168.1.3-thread-3][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] — Сериализация завершена, referenceType=componentReference, index=7, categoryName=PayRoute, ruleName=SubRule, chainName=chain2-2, class=com.nepxion.coroutine.test.service.impl.CServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=0 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a.
2017-12-23 19:13:43.679 INFO [Coroutine-192.168.1.3-thread-3][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] — Сериализация завершена, referenceType=componentReference, index=10, categoryName=PayRoute, ruleName=SubRule, chainName=chain2-2, class=com.nepxion.coroutine.test.service.impl.DServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=1 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a.
2017-12-23 19:13:43.679 INFO [Coroutine-192.168.1.3-thread-2][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] — Сериализация завершена, referenceType=componentReference, index=10, categoryName=PayRoute, ruleName=SubRule, chainName=chain2-2, class=com.nepxion.coroutine.test.service.impl.DServiceImpl, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=1 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
2017-12-23 19:13:43.680 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:61] — Сериализация завершена, referenceType=dependencyReference, index=13, categoryName=PayRoute, ruleName=SubRule, chainName=chain1-2, returnType=com.nepxion.coroutine.data.entity.CoroutineResult, spentTime=4 ms, id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375.
2017-12-23 19:13:43.680 INFO [Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:61] — Сериализация завершена, referenceType=dependencyReference, index=13, categoryName=PayRoute, ruleName=SubRule, chainName=chain1-1, returnType=com.nepxion.coroutine.data.entity.CoroutineResult, spentTime=4 ms, id=98c84565-ca73-42b8-a2e8-da4dee6df22a.
2017-12-23 19:13:43.692 INFO [Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.test.CoroutineTest$1$1:80] — Асинхронный обратный вызов: номер линии = 0, идентификатор = com.nepxion.coroutine.data.entity.CoroutineId@3ee322f7[
id=98c84565-ca73-42b8-a2e8-da4dee6df22a
categoryName=PayRoute
ruleName=Rule
], результат = com.nepxion.coroutine.data.entity.CoroutineResult@719c38e3[
id = com.nepxion.coroutine.data.entity.CoroutineId@14874a4f[
id=98c84565-ca73-42b8-a2e8-da4dee6df22a
categoryName=PayRoute
ruleName=SubRule
]
timestamp=0
result=(Start[0] -> A[0] -> B[0] -> C[0] -> D[0], Start[0] -> A[0] -> B[0] -> D[0] -> D[0]) -> A[0]) -> A[0]) -> B[0]) -> C[0]) -> D[0])
exception=<null>
].
2017-12-23 19:13:43.692 INFO [Timer-1][com.nepxion.coroutine.test.CoroutineTest$2:103] — Синхронный вызов: номер строки = 0, идентификатор = com.nepxion.coroutine.data.entity.CoroutineId@320ca662[
id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375
categoryName=PayRoute
ruleName=Rule
], результат = com.nepxion.coroutine.data.entity.CoroutineResult@475af95a[
id = com.nepxion.coroutine.data.entity.CoroutineId@3ce1ece3[
id=6fcb1456-fc34-49a0-9ad4-832fd5f3f375
categoryName=PayRoute
ruleName=SubRule
]
timestamp=0
result=(Start[0] -> A[0] -> B[0] -> C[0] -> D[0], Start[0] -> A[0] -> B[0] -> D[0] -> D[0]) -> A[0]) -> A[0]) -> B[0]) -> C[0]) -> D[0])
exception=<null>
]. **Вызов корутин в Dubbo и Thunder, агрегация распределённых API**
**Определение правил**
```xml
<?xml version="1.0" encoding="UTF-8"?>
<coroutine>
<rule version="1">
<component applicationContext="classpath*:dubbo-client-context-coroutine.xml">
<class id="aService">
<method index="1" method="doThen"/>
<method index="2" method="doWhen"/>
<method index="3" method="doMerge"/>
</class>
<class id="bService">
<method index="4" method="doThen"/>
<method index="5" method="doWhen"/>
<method index="6" method="doMerge"/>
</class>
</component>
<component applicationContext="classpath*:thunder-client-context-coroutine.xml">
<class id="cService">
<method index="7" method="doThen"/>
<method index="8" method="doWhen"/>
<method index="9" method="doMerge"/>
</class>
<class id="dService">
<method index="10" method="doThen"/>
<method index="11" method="doWhen"/>
<method index="12" method="doMerge"/>
</class>
</component>
<chain>
<when index="2,5"/>
<then index="9,10"/>
<when index="8,11"/>
<then index="3,4"/>
</chain>
</rule>
</coroutine>
Вызов входа
Запустите coroutine-spring-boot-dubbo-server-example
, чтобы запустить DubboServerApplication.java
.
Запустите coroutine-spring-boot-thunder-server-example
, чтобы запустить ThunderServerApplication.java
.
Запустите coroutine-spring-boot-client-example
, чтобы запустить CoroutineClientApplication.java
package com.nepxion.coroutine;
/**
* <p>Title: Nepxion Coroutine</p>
* <p>Description: Nepxion Coroutine For Distribution</p>
* <p>Copyright: Copyright (c) 2017</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.nepxion.coroutine.common.callback.CoroutineCallback;
import com.nepxion.coroutine.data.entity.CoroutineResult;
import com.nepxion.coroutine.framework.core.CoroutineManager;
@SpringBootApplication
@ComponentScan(basePackages = { "com.nepxion.coroutine" })
public class CoroutineClientApplication {
private static final Logger LOG = LoggerFactory.getLogger(CoroutineClientApplication.class);
public static void main(String[] args) throws Exception {
SpringApplication.run(CoroutineClientApplication.class, args);
// invokeRemote();
invokeLocal();
}
public static void invokeRemote() throws Exception {
// 请确保Zookeeper有对应的规则(运行CoroutineRuleRegistry相关方法)
// 从远程注册中心装载
// 启动和远程注册中心连接
CoroutineManager.start();
// 解析远端规则(支持子规则引用)
CoroutineManager.parseRemote("Distribution PayRoute", "Distribution Rule");
invokeAsync();
invokeSync();
}
public static void invokeLocal() throws Exception {
// 从本地装载
// 解析本地规则(不支持子规则引用)
CoroutineManager.parseLocal("Distribution PayRoute", "Distribution Rule", "rule.xml");
invokeAsync();
invokeSync();
}
public static void invokeAsync() {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
for (int i = 0; i < 1; i++) {
final int index = i % 5;
CoroutineManager.load().startAsync("Distribution PayRoute", "Distribution Rule", null, new String[] { "Start[" + index + "]" }, false, new CoroutineCallback<CoroutineResult<Object>>() {
@Override
``` 2017-12-23 19:20:29.201 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=9, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=cService, method=doMerge, parameterTypes=java.util.List, returnType=java.lang.String, spentTime=143 ms, id=956ab727-0e18-48aa-8334-1453c139fa23
2017-12-23 19:20:29.206 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=10, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=dService, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=3 ms, id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
2017-12-23 19:20:29.206 INFO [Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=10, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=dService, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=3 ms, id=956ab727-0e18-48aa-8334-1453c139fa23
2017-12-23 19:20:29.213 INFO [Promise-192.168.1.3-thread-4][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=8, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=cService, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=5 ms, id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
2017-12-23 19:20:29.214 INFO [Promise-192.168.1.3-thread-5][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=8, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=cService, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=6 ms, id=956ab727-0e18-48aa-8334-1453c139fa23
2017-12-23 19:20:29.214 INFO [Promise-192.168.1.3-thread-7][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=11, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=dService, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=6 ms, id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
2017-12-23 19:20:29.215 INFO [Promise-192.168.1.3-thread-6][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Parallel completed, referenceType=componentReference, index=11, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=dService, method=doWhen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=7 ms, id=956ab727-0e18-48aa-8334-1453c139fa23
2017-12-23 19:20:29.220 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=3, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=aService, method=doMerge, parameterTypes=java.util.List, returnType=java.lang.String, spentTime=5 ms, id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
2017-12-23 19:20:29.220 INFO [Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=3, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=aService, method=doMerge, parameterTypes=java.util.List, returnType=java.lang.String, spentTime=5 ms, id=956ab727-0e18-48aa-8334-1453c139fa23 **Перевод текста запроса на русский язык:**
[Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=4, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=bService, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=2 ms, id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
2017-12-23 19:20:29.222 INFO [Coroutine-192.168.1.3-thread-0][com.nepxion.coroutine.monitor.log.LogMonitorLauncher:55] - Serial completed, referenceType=componentReference, index=4, categoryName=Distribution PayRoute, ruleName=Distribution Rule, chainName=null, classId=bService, method=doThen, parameterTypes=java.lang.String, returnType=java.lang.String, spentTime=2 ms, id=956ab727-0e18-48aa-8334-1453c139fa23
2017-12-23 19:20:29.223 INFO [Timer-1][com.nepxion.coroutine.CoroutineClientApplication$2:96] - 同步调用结果: 线程序号=0, id=com.nepxion.coroutine.data.entity.CoroutineId@2295f70c[
id=956ab727-0e18-48aa-8334-1453c139fa23
categoryName=Distribution PayRoute
ruleName=Distribution Rule
], result=((Start[0] -> A[0] -> C[0] , Start[0] -> B[0] -> C[0]) -> D[0]) -> C[0]) -> A[0]) , (Start[0] -> A[0] -> C[0] , Start[0] -> B[0] -> C[0]) -> D[0]) -> D[0]) -> A[0])) -> B[0]))
2017-12-23 19:20:29.223 INFO [Coroutine-192.168.1.3-thread-1][com.nepxion.coroutine.CoroutineClientApplication$1$1:73] - 异步回调结果: 线程序号=0, id=com.nepxion.coroutine.data.entity.CoroutineId@51baebd3[
id=b22a77b6-0776-49a1-a6bb-e15268ffd0c1
categoryName=Distribution PayRoute
ruleName=Distribution Rule
], result=((Start[0] -> A[0] -> C[0] , Start[0] -> B[0] -> C[0]) -> D[0]) -> C[0]) -> A[0]) , (Start[0] -> A[0] -> C[0] , Start[0] -> B[0] -> C[0]) -> D[0]) -> D[0]) -> A[0])) -> B[0]))
## 请联系我
微信、钉钉、公众号和文档




## Star走势图
[](https://starchart.cc/Nepxion/Coroutine)
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )