convertAndSend vs. SendTo annotaiton

Viewed 853

I have the following piece of code:

@Controller
@EnableScheduling
public class QuoteController {

    @Scheduled(fixedDelay=5000)
    @SendTo(value="/topic/quote")
    public String sendPrice() {
        return "message from scheduler";
    }
}

And it doesn't send the message to the channel. But the following code works:

@Controller
@EnableScheduling
public class QuoteController {
    @Autowired
    public SimpMessageSendingOperations messagingTemplate;

    @Scheduled(fixedDelay=5000)
    public String sendPrice() {
        messagingTemplate.convertAndSend("/topic/quote", "message from scheduler");
    }
}
1 Answers

We should use @SendTo annotation only by functions that called by websocket, it's mean functions annocated with @MessageMapping.

If you want to send message to queue in other way you should use messagingTemplate.convertAndSend.

Example for @SendTo:

@MessageMapping("/hello") // from websocket
@SendTo("/topic/bla")
public String foo1(String message) {
    return message;
}

Example for .convertAndSend:

@Autowired
private SimpMessagingTemplate template;

@GetMapping("/{msg}") //from GET request
public void foo2(@PathVariable String msg) {
    template.convertAndSend("/topic/bla", msg);
}
Related