Solon v3.3.3

flow - 事件总线(事件广播、解耦)

</> markdown

1、流事件总线

流事件总线(基于大米事件总线 - DamiBus),是上下文级别的(或实例级别的)。可以为扩展提供“解耦”支持。

支持三种交互接口(具体参考 DamiBus):

  • 只发送
  • 发送,要求一个答复(监听时,可以答复一次)
  • 发送,可以有多个答复(监听时,可以答复多次)

支持泛型(因为支持答复,所以需要同时指定 "发" 与 "收" 的泛型)

context.<String,String>eventBus()

不使用泛型(发、收都表示为 Object)

context.eventBus()

2、配置应用示例

# flow/f1.chain.yml
id: f1
layout:
  - task: |
      //发送事件
      context.eventBus().send("demo.topic", "hello1");
  - task: |
      //发送事件并做为请求(要求给答复)//使用泛型
      String rst = context.<String,String>eventBus().sendAndRequest("demo.topic", "hello2"); 
      System.out.println(rst);
  - task: |
      //发送事件并做为请求(要求给答复)//使用泛型 //再使用默认值(如果没有订阅)
      String rst = context.<String,String>eventBus().sendAndRequest("demo.topic", "hello2", ()-> "def"); 
      System.out.println(rst);

3、代码应用示例

public class DemoTest {
    @Test
    public void case1() throws Exception {
        FlowEngine flowEngine = FlowEngine.newInstance();
        flowEngine.load("classpath:flow/*.yml");

        FlowContext context = new FlowContext();
        
        //事件监听(即订阅)
        context.eventBus().listen("demo.topic", event -> {
            System.out.println(event.getContent());
            
            if(event.isRequest()){
                event.reply("ok"); //如果是请求,则给予答复
            }
        });

        flowEngine.eval("f1", context);
    }
}