Home > Blockchain >  how to write a function which produces data to different bindings based on custom logic
how to write a function which produces data to different bindings based on custom logic

Time:06-16

A regular spring cloud stream function looks like this (taken from the docs):

@Bean
public Function<String, String> toUpperCase() {
    return s -> s.toUpperCase();
}

Considering not using a reactive approach, I wonder whether it's possible to make different transformations based on custom logic and/or send the result to a different "out" binding? Something like this:

@Bean
public Function<String, String> transform() {
    return s -> {
      if (s.equals("A")) {
        return s.toUpperCase();       //this wants to be sent to toUpperCase-out-0
      } else if (s.equals("B")) {
        return s.toLowerCase();       //this wants to be sent to toLowerCase-out-0
      } else {
        return "unsupported";         //this wants to be sent to unsupported-out-0
      }
    };
}

Also, here we have the same return type (String) but maybe it could be required to return objects of different classes from each branch (by using Object/astract class/etc. as a return type of the whole function).

I can imagine a solution with a Consumer instead of Function in which we make different StreamBridge calls, but maybe it's possible to do the same with a Function?

CodePudding user response:

Don't use a Function, use a Consumer instead and send the outputs using the StreamBridge.

https://docs.spring.io/spring-cloud-stream/docs/current/reference/html/spring-cloud-stream.html#_sending_arbitrary_data_to_an_output_e_g_foreign_event_driven_sources

  • Related