springboot整合webSocket的使用

引入jar包

<dependency><!-- 5.引入websocket-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

1 配置config

package com.test.domi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
// @EnableWebSocketMessageBroker注解用于开启使用STOMP协议来传输基于代理(MessageBroker)的消息,这时候控制器(controller)
// 开始支持@MessageMapping,就像是使用@requestMapping一样。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

/*将"/hello"路径注册为STOMP端点,这个路径与发送和接收消息的目的路径有所不同,这是一个端点,客户端在订阅或发布消息到目的地址前,要连接该端点,
* 即用户发送请求url="/applicationName/hello"与STOMP server进行连接。之后再转发到订阅url;
* PS:端点的作用——客户端在订阅或发布消息到目的地址前,要连接该端点。

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //注册一个Stomp的节点(endpoint),并指定使用SockJS协议。记得设置跨域
        stompEndpointRegistry.addEndpoint("/endpointAric").setAllowedOrigins("*").withSockJS();
    }

/**
* 配置了一个简单的消息代理,如果不重载,默认情况下回自动配置一个简单的内存消息代理,用来处理以"/topic"为前缀的消息。这里重载configureMessageBroker()方法,
* 消息代理将会处理前缀为"/topic"和"/queue"的消息。

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //服务端发送消息给客户端的域,多个用逗号隔开
        registry.enableSimpleBroker("/topic");
        //定义一对一推送的时候前缀
        //registry.setUserDestinationPrefix("/user");
        //定义websoket前缀
        //registry.setApplicationDestinationPrefixes("/ws-push");
    }

   
}

  

2 controller

package com.test.domi.controller;

import com.google.common.collect.Lists;
import com.test.domi.service.impl.WebSocketService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import java.util.List;

@Controller
public class WsController {

    @Resource
    private SimpMessagingTemplate template;

    @MessageMapping("/welcome")//@MessageMapping和@RequestMapping功能类似,用于设置URL映射地址,浏览器向服务器发起请求,需要通过该地址。
    public void say(String message) throws Exception {
        template.convertAndSend("/topic/getResponse", message);
    }

}

 

3 前台页面

  

原文地址:https://www.cnblogs.com/domi22/p/9460299.html