springboot整合WebSocket,实现聊天室功能!
一、增加WebSocket依赖
<!-- springboot整合WebSocket进行全双工通信(1) -->
<!-- websocket相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 前端库,使用jar包的形式对前端库进行统一管理,使用webjar添加到项目中的前端库,在springboot项目中已经默认添加了静态资源过滤,因此可以直接使用 -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator-core</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
二、定义配置类,实现WebSocketMessageBrokerConfigurer接口,设定消息代理的前缀及支持sockjs的代码
package com.steno.propertiestest.common;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* springboot整合WebSocket进行全双工通信(2)
* 自定义类实现WebSocketMessageBrokerConfigurer接口,实现特定方法
*/
@Configuration //定义配置类
@EnableWebSocketMessageBroker //开启WebSocket消息代理
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* @param registry 消息代理注册
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
/*
* 设置消息代理的前缀,即:如果消息的前缀是"/topic"就会将消息转发给消息代理(broker),
* 再由消息代理降消息广播给当前连接的客户端
*/
registry.enableSimpleBroker("/topic");
/*
* 配置一个或多个前缀,通过这些前缀过滤出需要被注解方法处理的消息!
* 如:前缀为"/app"的destionation(目的地)可以通过@MessageMapping注解的方法处理,
* 而其他destionnation(如"/topic"、"/queue")将被直接交给broker(消息代理)处理。
*/
registry.setApplicationDestinationPrefixes("/app");
}
/**
* @param registry
*/
@Override
public