Search code examples
javaspringreactor

Select events matching a key using Reactor


Using reactor(https://github.com/reactor/reactor) i notify a few events like

 commandReactor.notify("CREATE_CUSTOMER", Event.wrap(customer));
 commandReactor.notify("CREATE_ORDER", Event.wrap(order));

How do i implement a selector which selects all events starting with "CREATE"? Something like

@Selector(value = "CREATE*", reactor = "@commandReactor")

Thanks in advance.


Solution

  • You can use the RegexSelector [1] to do that:

        commandReactor.notify("CREATE_(.+)", Event.wrap(obj));
    

    or, using the annotations:

        @Selector(value = "CREATE_(.+)", type = SelectorType.REGEX)
    

    Then in your handler, you can inspect the capture group by looking at the header for group1 to groupN:

    new Consumer<Event<Object>>>() {
      public void accept(Event<?> ev) {
        String type = ev.getHeaders().get("group1");
        if("CUSTOMER".equals(type)) {
          // handle customers
        } else if("ORDER".equals(type)) {
          // handle orders
        }
    }
    

    [1] - http://reactor.github.io/docs/api/reactor/event/selector/RegexSelector.html