Sample code to publish a message to a topic using spring cloud stream api

Hi @matthesu,
Great question! We’ve actually been working with the engineering team over at Spring to improve how Spring Cloud Stream (SCSt) handles publishing to dynamic destinations just over the past few months.

There’s going to be 2 ways of doing this:

  1. [This works as of v3.0.5 of Spring Cloud Stream released at the end of May] Basically you would setup a Consumer function and then send to dynamic topics by injecting a StreamBridge object into your function and sending using that. StreamBridge is built into SCSt. and is smart enough to find the configured binder for you. It also caches a configurable number of channels using the spring.cloud.stream.dynamic-destination-cache-size property which has a default of 10.
    @Bean Consumer<String> myConsumerFunction(StreamBridge streamBridge){
    	return input -> {
    		    String topic = getMyTopicUsingLogic(input);
		    streamBridge.send(topic, input);
    	};
    }
  1. [This will be available in the next Solace Binder release] A new SCSt. header was reserved in v3.0.5. This header, “scst_targetDestination” , basically tells the binder (if the binder supports it) to ignore the default destination the function is bound to and instead send to the destination specified by the header. So once this is available you would essentially configure your SCSt. yml with a “default” destination and then override it for each message, or only when you need to. The benefit of this route is that the SCSt. framework doesn’t create channels, cache them, etc so if you’re always going to be sending to a different topic I would recommend going with this option once it’s available.
          @Bean
            public Function<Message<String>, Message<String>> functionName() {
                        return input -> {
                                    String topic = getMyTopicUsingLogic(input);
                                    MessageBuilder<String> outboundMessage = MessageBuilder.withPayload("whatever").setHeader("scst_targetDestination",
                                                            topic);
                        };
            }

Hope that helps! Once our binder supports this we’ll be rolling out more examples around this as well :slight_smile:
-Marc