首页 > 解决方案 > convertAndSend 与 SendTo 注释

问题描述

我有以下代码:

@Controller
@EnableScheduling
public class QuoteController {

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

而且它不会将消息发送到频道。但以下代码有效:

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

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

标签: javaspring

解决方案


我们应该@SendTo只对被 websocket 调用的函数使用注解,这意味着使用@MessageMapping.

如果您想以其他方式将消息发送到队列,您应该使用messagingTemplate.convertAndSend.

示例@SendTo

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

示例.convertAndSend

@Autowired
private SimpMessagingTemplate template;

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

推荐阅读