Spring Cloud Stream and @Publisher annotation compatiblity

后端 未结 2 1240
野的像风
野的像风 2021-01-20 18:35

Since Spring Cloud Stream has not an annotation for sending a new message to a stream (@SendTo only works when @StreamListener is declared), I tried to use Spring Integratio

相关标签:
2条回答
  • 2021-01-20 18:58

    Why not just send the message to a stream manually, like below.

    @Component
    @Configuration
    @EnableBinding(Processor.class)
    public class Sender {
    
        @Autowired
        private Processor processor;
    
        public void send(String message) {
    
            processor.output().send(MessageBuilder.withPayload(message).build());
    
        }
    
    }
    

    You can test it through the tester.

    @SpringBootTest
    public class SenderTest {
    
        @Autowired
        private MessageCollector messageCollector;
    
        @Autowired
        private Processor processor;
    
        @Autowired
        private Sender sender;
    
        @SuppressWarnings("unchecked")
        @Test
        public void testSend() throws Exception{
    
            sender.send("Hi!");
            Message<String> message = (Message<String>) this.messageCollector.forChannel(this.processor.output()).poll(1, TimeUnit.SECONDS);
            String messageData = message.getPayload().toString();
            System.out.println(messageData);
    
        }
    
    }
    

    You should see "Hi!" in the console.

    0 讨论(0)
  • 2021-01-20 19:00

    Since you use a @Publisher annotation in your ExampleService, it is proxied for that publishing stuff.

    Only the way to overcome the issue is to expose an interface for your ExampleService and inject already that one into your test class:

    public interface ExampleServiceInterface {
    
         String sendMessage(String message);
    
    }
    
    ...
    
    public class ExampleService implements ExampleServiceInterface {
    
    ...
    
    
    @Autowired
    private ExampleServiceInterface exampleService;
    

    On the other hand it looks like your ExampleService.sendMessage() does nothing with the message, so you may consider to use a @MessagingGateway on some interface instead: https://docs.spring.io/spring-integration/reference/html/messaging-endpoints-chapter.html#gateway

    0 讨论(0)
提交回复
热议问题