java - 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");
}
}
解决方案
我们应该@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);
}
推荐阅读
- python - 如何使用 os.remove() 删除所有电子邮件文件?通过电子邮件发送到 TFS 票
- aurelia - Aurelia Kendo Grid - 搜索栏不显示
- python - python上下文协议:为什么__enter__和__exit__方法不能在对象中定义?
- math - 不能让数学随机在两个不同的地方工作
- .net-core - 经管理员同意的 MS-Graph 读取任务
- java - 解析字符串的递归方式
- c# - C#中子项的嵌套foreach
- elixir - 如何将请求参数填充到 Plug.Conn 连接中?
- r - 使用 lapply 在数据框中填充 NA 值
- android - 离子应用程序 - 登录页面 - 文本框在其他用户操作之前不会打开键盘