# chains-spring-boot-component **Repository Path**: MiMose/chains-spring-boot-component ## Basic Information - **Project Name**: chains-spring-boot-component - **Description**: 📿📿 链路组件,通过链式编程实现链路调用。集成后可通过该组件定制出有序的链路,从而实现如拦截器链路、规则链路等功能 - **Primary Language**: Java - **License**: GPL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 6 - **Forks**: 2 - **Created**: 2020-08-28 - **Last Updated**: 2025-05-15 ## Categories & Tags **Categories**: distributed-service **Tags**: None ## README ### **CHAINS-SPRING-BOOT-COMPONENT** #### 链路组件 ### 使用方法: 1、创建对应的链路类,继承Chain,首先实现里面的myName()方法,为链路添加一个唯一的标识;若存在满足的链路类,则直接使用 ~~~ public class ExampleChain extends Chain { @Override public void withInvokers() { // 第3步完成后设置 } @Override public String myName() { // 这个字符串保证唯一,使用该字符串来获取对应的链路 return "example" } } ~~~ 2、创建对应的请求实体,继承RequestBaseDto; 创建对应的响应实体,继承ResponseBaseDto;若已存在满足的实体,则直接使用 ~~~ public class ExampleRequestDto extends RequestBaseDto { // 该实体用于传递链路处理的参数 private String param1; private Object param2; } public class ExampleResponseDto extends ResponseBaseDto { // 该实体用于返回处理后的结果,在链路的各个处理器中都能使用 private String result1; @JSONField(format = "yyyy-MM-dd") private Date result2; } ~~~ 3、创建对应的处理类,继承Invoker;若存在满足的处理类,则直接使用 ~~~ public class ExampleInvoker_one extends Invoker { @Override public Response invoke0(ExampleRequestDto request, Response tResponse) { // 可以通过该方法获取到上个处理器的结果。 当该处理器是第一个处理器时,将获取到一个新的结果,否则获取到上个处理结果 ExampleResponseDto response = super.getLastResponse(tResponse, ExampleResponseDto.builder().build()); // 具体的处理逻辑 // do something // 在处理后,可以根据处理情况,选择是否要中断本次链路 // 若要中断,则返回 return tResponse.end(true, response); // 若要继续进行,则返回 return tResponse.end(false, response); } } ~~~ 4、实现具体链路类中的withInvokers方法,初始化该链路的所有处理类 ~~~ public class ExampleChain extends Chain { @Override public void withInvokers() { // 第3步完成后设置 invoker = new ExampleInvoker_one(); //若该链路有2个及2个以上的处理器,通过setNext来进行处理器的增加 invoker.setNext(new ExampleInvoker_two()); invoker.setNext(new ExampleInvoker_three()); // ... } @Override public String myName() { // 这个字符串保证唯一,使用该字符串来获取对应的链路 return "example" } } ~~~ 5、在业务代码里使用链路: 5.1、同步调用获取结果: ~~~ // 创建参数、调用链路: ExampleRequestDto requestDto = ExampleRequestDto.builder().param1("参数1").param2("参数2").build(); Response resp = (Response) Chain.newChain("example").invoke(Request._Request(requestDto)); 获取对应链路 -------> 使用链路中的处理器进行Request处理 // 获取结果 ExampleResponseDto respDto = resp.getResponse(); ~~~ 5.2、异步调动回调结果: 为避免主线程执行过程中,由于暂时不需要该结果,而链路执行会阻塞主线程,导致的主线程执行时间变长,使用Task来进行异步调用获取结果,不阻塞主线程 ~~~ // 创建参数,先在主线程中获取到链路的task ExampleRequestDto requestDto = ExampleRequestDto.builder().param1("参数1").param2("参数2").build(); ResponseAsyn resp = (ResponseAsyn) Chain.newChain("example").withSync().invoke(Request._Request(requestDto)); 获取对应链路 -----开启异步任务模式---> 使用链路中的处理器进行Request处理 // 主线程继续执行 // 主线程业务逻辑.... // 到了需要获取链路结果的时候,调用回调方法获取结果(需要传入超时时间[秒],避免链路长时间处理,影响业务) ExampleResponseDto responseDto = resp.getResponse(3); ~~~