Spring Boot + WebSocket实现消息推送

Spring Boot + WebSocket实现消息推送

WebSocket介绍

WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信,允许服务器主动发送信息给客户端。

Spring Boot对WebSocket提供了支持,用Spring Boot能更好的对WebSocket整合

pom.xml(部分)

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-websocketartifactId>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

...


<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>webjars-locatorartifactId>
dependency>
<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>sockjs-clientartifactId>
    <version>1.0.2version>
dependency>
<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>stomp-websocketartifactId>
    <version>2.3.3version>
dependency>
<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>bootstrapartifactId>
    <version>3.3.7version>
dependency>
<dependency>
    <groupId>org.webjarsgroupId>
    <artifactId>jqueryartifactId>
    <version>3.1.0version>
dependency>

WebSocket 配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置一个/topic消息代理
        config.enableSimpleBroker("/topic");
    }


    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
            .addEndpoint("/socket/chat")  // 注册一个STOMP的endpoint
            .setAllowedOrigins("*")  // 允许跨域
            .withSockJS();  //指定使用SockJS协议
    }
}

消息实体

@Data
@AllArgsConstructor
@NoArgsConstructor
public class WebSocketMessage {

    private String message;
    private LocalDateTime time;

}

WebSocket控制器

@RestController
public class WebSocketController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @MessageMapping("/welcome") //当浏览器向服务端发送请求时,通过@MessageMapping映射/welcome这个地址,类似于@ResponseMapping
    @SendTo("/topic/getResponse")//当服务器有消息时,会对订阅了@SendTo中的路径的浏览器发送消息
    public WebSocketMessage say(WebSocketMessage message) {
        logger.info("Web socket message is {}", message);
        try {
            //睡眠1秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new WebSocketMessage(message.getMessage(), LocalDateTime.now());
    }
}

编写webSocket.html,使用thymeleaf模板引擎


<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>SpringBoot实现广播式WebSockettitle>
    <script src="/webjars/jquery/jquery.min.js">script>
    <script src="/webjars/sockjs-client/sockjs.min.js">script>
    <script src="/webjars/stomp-websocket/stomp.min.js">script>
head>
<body>
<noscript><h2 style="color:#ff0000">抱歉,您的浏览器不支持改功能!h2>noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">连接button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接button>
    div>
    <div id="conversationDiv">
        <labe消息label><input type="text" id="name" />
        <button id="sendMessage" onclick="sendMessage();">发送button>
        <p id="response">p>
    div>
div>
body>
<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected){
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $("#response").html();
    }

    function connect(){
        var socket = new SockJS('/socket/chat'); //连接SockJS的endpoint名称为"/socket/chat"
        stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
        stompClient.connect({},function(frame){//连接WebSocket服务端
            setConnected(true);
            console.log('Connected:' + frame);
            //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息,这个是在控制器的@SentTo中定义的
            stompClient.subscribe('/topic/getResponse',function(response){
                showResponse(response.body);
            });
        });
    }

    function disconnect(){
        if(stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendMessage(){
        var messgae = $("#messgae").val();
        //通过stompClient.send向/welcome 目标(destination)发送消息,这个是在控制器的@MessageMapping中定义的
        stompClient.send("/welcome",{},JSON.stringify({'message':messgae}));
    }

    function showResponse(message){
        var response = $("#response");
        response.html(message);
        console.log(message);
    }
script>
html>

配置viewController

 @Controller
public class WebMvcConfig extends WebMvcConfigurerAdapter{

    /**
     * 配置viewController,提供映射路径
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/webSocket").setViewName("/webSocket");
    }
}

至此,Spring Boot整合WebSocket广播式消息推送实现。

当项目整合了oauth2验证时,WebSocket连接就会报错

解决方法

WebSecurityConfigurer

@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()                .authorizeRequests()
            .antMatchers("/socket/chat/**").permitAll()
        ;
    }
}

WebSocketSecurityConfiguration

@Configuration
public class WebSocketSecurityConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {

    @Override
    protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
        messages.anyMessage().permitAll();
    }

    @Override
    protected boolean sameOriginDisabled() {
        return true;
    }
}

你可能感兴趣的:(Spring,Boot)