6、Spring Session-WebSocket集成

5、WebSocket集成

Spring Session提供了和Spring Websocket透明集成的支持。

Spring Session的Websocket支持仅适用于Spring的Websocket支持,具体来说他不能直接支持JSR-356。这是由于JSR-356没有拦截进入Websocket消息的机制。

5.1. 为什么要集成Spring Session和Websocket?

为什么在使用Websocket的时候我们需要Spring Session呢?

考虑一个大多数工作都是通过HTTP请求来完成的Email应用,然而,这个应用也嵌入了一个通过Websocket来完成工作的聊天应用。如果一个用户正在和另外的人活跃的聊天,我们的HttpSession就不应该超时,因为这将会是一个非常糟糕的体验。然而,JSR-356就这样做了。

另外一个问题就是根据JSR-356,如果HttpSession超时,所有使用这个HttpSession创建的WebSocket和已认证的用户都会被强制关闭。那就意味着如果我们正在我们的应用中活跃的聊天且我们没有使用HttpSession,那一会儿之后我们将会从我们的会话中断开连接。

5.2. Websocket使用

WebSocket 样例(https://github.com/spring-projects/spring-session/tree/2.0.0.M4/samples/boot/websocket)提供了一个如何整合Spring Session和WebSocket的可执行样例。你可以按照以下的基础步骤集成,但是在你集成自己的应用时,推荐遵循详细的WebSocket指南。

5.2.1. HttpSession集成

使用WebSocket集成之前,你首先应该确定你已经集成HttpSession且能够正常工作。

5.2.2. Spring配置

在典型的Spring WebSocket应用中,用户需要继承AbstractWebSocketMessageBrokerConfigurer。比如,配置看起来如下:

@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/messages").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue/", "/topic/");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

我们可以很容易的更新我们配置去使用Spring Session的WebSocket支持。例如:

src/main/java/samples/config/WebSocketConfig.java
@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig
        extends AbstractSessionWebSocketMessageBrokerConfigurer<Session> { 

    protected void configureStompEndpoints(StompEndpointRegistry registry) { 
        registry.addEndpoint("/messages").withSockJS();
    }

    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/queue/", "/topic/");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

在Spring Session支持中,我们只需要改变两件事情:

  1. 我们继承AbstractSessionWebSocketMessageBrokerConfigurer代替AbstractWebSocketMessageBrokerConfigurer 。
  2. 重命名registerStompEndpoints方法为configureStompEndpoints

AbstractSessionWebSocketMessageBrokerConfigurer在幕后做了什么呢?

  1. WebSocketConnectHandlerDecoratorFactory作为WebSocketHandlerDecoratorFactory被添加到WebSocketTransportRegistration。这就确保了包含WebSocketSession的SessionConnectEvent可以被自动启动。Spring Session终止之后,WebSocketSession需要去终止所有开启的WebSocket链接。
  2. SessionRepositoryMessageInterceptor作为HandshakeInterceptor被添加到StompWebSocketEndpointRegistration中。这就确保了会话已经被添加到WebSocket的属性中,以便更新上一次访问的时间。
  3. SessionRepositoryMessageInterceptor作为ChannelInterceptor被添加到我们的入站ChannelRegistration中。这就确保每次入站消息都会被接收,Spring Session的最后一次访问时间也会被更新。
  4. WebSocketRegistryListener作为一个Spring Bean被创建。这就确保了我们的所有Session id都会被映射到一个关联的WebSocket链接。通过维护这个映射,当Spring Session终止的时候我们就可以关闭所有的WebSocket链接。

原文:https://docs.spring.io/spring-session/docs/2.0.0.M4/reference/html5/#websocket

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
netty-websocket-spring-boot-starter是一个基于Netty实现的WebSocket框架,可以方便地在Spring Boot应用中集成WebSocket功能。使用该框架可以快速构建实时通信、消息推送等功能。 下面是一个使用netty-websocket-spring-boot-starter的简单案例: 1. 在pom.xml中添加依赖: ```xml <dependency> <groupId>com.github.wujiuye</groupId> <artifactId>netty-websocket-spring-boot-starter</artifactId> <version>1.0.0.RELEASE</version> </dependency> ``` 2. 编写WebSocket处理器 ```java @ServerEndpoint("/websocket/{userId}") @Component public class WebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); private Session session; private String userId; @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { this.session = session; this.userId = userId; logger.info("WebSocket连接建立,userId: {}", userId); } @OnMessage public void onMessage(String message) { logger.info("收到来自客户端的消息:{}", message); sendMessage("服务端已收到消息:" + message); } @OnClose public void onClose() { logger.info("WebSocket连接关闭,userId: {}", userId); } @OnError public void onError(Throwable t) { logger.error("WebSocket连接异常,userId: {}", userId, t); } public void sendMessage(String message) { try { this.session.getBasicRemote().sendText(message); } catch (IOException e) { logger.error("发送WebSocket消息失败,userId: {}", userId, e); } } } ``` 3. 配置WebSocket 在配置类中添加@EnableWebSocket注解,启用WebSocket功能,同时,也可以配置WebSocket的一些参数,例如端口号、路径等。 ```java @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Autowired private WebSocketHandler webSocketHandler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(webSocketHandler, "/websocket/{userId}") .setAllowedOrigins("*"); } } ``` 4. 测试WebSocket 使用浏览器或WebSocket客户端连接WebSocket服务端,例如:ws://localhost:8080/websocket/123,其中123为userId。 以上就是一个简单的netty-websocket-spring-boot-starter使用案例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值