【问题标题】:Websocket in Spring and JavaSpring和Java中的Websocket
【发布时间】:2014-02-02 16:02:15
【问题描述】:

对于我在 Spring 中构建的项目,我想实现 websocket。我找到了 STOMP 形式的解决方案,但我找不到向单个用户发送 websocket 消息的方法,只能向所有客户端进行完整广播。有哪些可以轻松插入 Spring 并且我可以用来发送和接收消息的好选择?我在 Spring 中有一个自滚动的用户系统(而不是使用 Spring Security),我想将它与它联系起来。

编辑:我想指出,我想要一个能够优雅地降级到其他通信协议的解决方案,就像 socket.io 那样。

【问题讨论】:

标签: java spring spring-mvc websocket stomp


【解决方案1】:

要使用 Spring 和 websockets,请查看新的 Spring Websocket support in Spring 4,这是关于它的 presentation。

根据文档,Spring支持单用户连接,以及广播:

Spring Framework 允许@Controller 类同时拥有 HTTP 请求 处理和 WebSocket 消息处理方法。此外,一个弹簧 MVC 请求处理方法,或任何应用程序方法 没关系,可以轻松地向所有感兴趣的 WebSocket 广播消息 客户或特定用户。

这是一个广播示例,您已经可以这样做了:

@Controller
public class GreetingController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Greeting greeting(HelloMessage message) throws Exception {
        Thread.sleep(3000); // simulated delay
        return new Greeting("Hello, " + message.getName() + "!");
    }

}

根据文档,不做广播只回复主叫客户的方法是省略@SendTo注解:

默认情况下,@SubscribeMapping 方法的返回值被发送 作为消息直接返回给连接的客户端并且不传递 通过经纪人。这对于实现请求-回复很有用 消息交互;

【讨论】:

  • 好吧,对于优雅的降级,它们似乎都指的是 STOMP,但我不知道如何使用 STOMP 向单个人发送消息,仅用于广播。
  • 我已经更新了答案,也支持单客户端连接
  • 对这个问题有任何想法吗? :) stackoverflow.com/questions/21565598/…
【解决方案2】:

这应该会有所帮助

private final SimpMessageSendingOperations messagingTemplate;

List<String> messages = new ArrayList<>(Arrays.asList("Bar","Foo"));

@AutoWired
public YourConstructor(SimpMessageSendingOperations messagingTemplate){
       this.messagingTemplate = messagingTemplate;
}

@Scheduled(fixedDelay=1500)
public void sendMessages() {

for (String message : messages) {
   this.messagingTemplate.convertAndSendToUser(user, "/queue/messages", message);
        }
}

PS:定时任务的@Scheduled Annotation

【讨论】:

    猜你喜欢
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2019-06-11
    • 2019-06-16
    • 2018-09-25
    相关资源
    最近更新 更多