第一步:配置Spring
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
第二步:配置WebSocket
我采用的是使用Configurer类和 Annotation来进行WebSocket配置。
首先要创建一个类,继承WebSocketMessageBrokerConfigurer 或者继承AbstractSecurityWebSocketMessageBrokerConfigurer,并且在类上加上annotation:@Configuration和@EnableWebSocketMessageBroker。这样,Spring就会将这个类当做配置类,并且打开WebSocket。
AbstractSecurityWebSocketMessageBrokerConfigurer这个类在spring-security-config这个包中
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;
@Configuration
@EnableWebSocketMessageBroker
@EnableConfigurationProperties(StompWebSocketProperties.class)
public class StompWebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Autowired
private StompWebSocketProperties stompWebSocketProperties;
//添加这个Endpoint,这样在网页中就可以通过websocket连接上服务了
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("endpoint").setAllowedOrigins("*").withSockJS();
}
/**
* 配置消息代理
*
* @param registry
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
System.out.println("服务器启动成功");
//这里设置的simple broker是指可以订阅的地址,也就是服务器可以发送的地址
registry.enableSimpleBroker("/topic");
registry.setUserDestinationPrefix("/user");
}
@Override
protected boolean sameOriginDisabled() {
return true;
}
/**
* 消息传输参数配置
*/
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
// 设置消息字节数大小
registry.setMessageSizeLimit(stompWebSocketProperties.getMessageSizeLimit())
// 设置消息缓存大小x
.setSendBufferSizeLimit(stompWebSocketProperties.getSendBufferSizeLimit())
// 设置消息发送时间限制毫秒
.setSendTimeLimit(stompWebSocketProperties.getSendTimeLimit());
}
/**
* 业务需要自定义
*/
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages.anyMessage().permitAll();
}
/**
* 输出通道参数设置
*/
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.taskExecutor().corePoolSize(stompWebSocketProperties.getCorePoolSize())
.maxPoolSize(stompWebSocketProperties.getMaxPoolSize())
.keepAliveSeconds(stompWebSocketProperties.getKeepAliveSeconds());
}
}
configureMessageBroker 方法用于配置消息代理,registerStompEndpoints 方法用于注册 WebSocket 端点。enableSimpleBroker("/topic") 表示启用简单的消息代理,并将消息发送到 /topic 目的地。addEndpoint("/endpoint").withSockJS() 表示注册一个 WebSocket 端点,并启用 SockJS 支持
定义一个发送消息的类:前端订阅后,后端 有消息时,可以通过此方法发送到前端
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
@Component
public class StompMsgSendMessage {
@Autowired
private SimpMessagingTemplate messagingTemplate;
public void sendMsgToClient(String topic, Object o) {
if (StringUtils.isBlank(topic)) {
return;
}
messagingTemplate.convertAndSend(topic, o);
}
}
前端使用的是:SockJS和Stomp实现websocket
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
</head>
<body>
<div id="chatroom">
<ul id="messages"></ul>
</div>
<form id="form">
<input type="text" id="input" placeholder="Type your message here...">
<button type="submit">Send</button>
</form>
<script>
var socket = new SockJS('http://localhost:8080/TESTAPP/endpoint');
var stompClient = Stomp.over(socket);
var messagesElement = document.getElementById('messages');
var formElement = document.getElementById('form');
var inputElement = document.getElementById('input');
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/device/upgrade', function (message) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(message.body));
messagesElement.appendChild(li);
});
});
formElement.addEventListener('submit', function (event) {
event.preventDefault();
stompClient.send("/send", {}, inputElement.value); //后端需要写controller方法接收消息
inputElement.value = '';
});
</script>
</body>
</html>
后端Controller中模拟发消息 到前端的订阅地址:topic/device/upgrade
@Autowired
private StompMsgSendMessage stompMsgSendMessage;
@GetMapping("/upgradeok")
public ResponseMessage<String> upgradeok() {
log.info("######测试出发升级完成的通知");
stompMsgSendMessage.sendMsgToClient("/topic/device/upgrade", "upgarde sunccess "+ new Date());
return ResponseMessage.ok("ok");
}
测试结果:
后端服务启动后,打开html页面:
websocket连接成功
消息订阅:
postman调用controller中方法模拟发消息: