springboot业务功能实战(四)告别轮询,websocket的集成使用

简介: springboot业务功能实战(四)告别轮询,websocket的集成使用


后端代码

首先加入pom文件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <!-- <version>1.3.5.RELEASE</version> -->
        </dependency>

加入配置类

@Configuration
public class WebSocketConfig {
    /**
     *  注入ServerEndpointExporter,
     *  这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

加入连接发送消息方法

@Component
@ServerEndpoint("/websocket/{userName}")
// 此注解相当于设置访问URL
public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    private static Map<String, Session> sessionPool = new HashMap<String, Session>();
    private final static Logger logger = LoggerFactory.getLogger(LoginIntercept.class);
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userName") String userName) {
        this.session = session;
        webSockets.add(this);
        if (sessionPool.containsKey(userName)) {
            sessionPool.put(userName + String.valueOf(session.getId()), session);
        } else {
            sessionPool.put(userName, session);
        }
        logger.info("【websocket消息】有新的连接,总数为:" + webSockets.size());
    }
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        logger.info("【websocket消息】连接断开,总数为:" + webSockets.size());
    }
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客户端消息:" + message);
    }
    /**
     * 功能描述: 此为广播消息
     *
     * @param: [message] (消息)
     * @return: void ()
     */
    public void sendAllMessage(String message) {
        for (WebSocket webSocket : webSockets) {
            logger.info("【websocket消息】广播消息:" + message);
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 功能描述:此为单点消息 (发送文本) 现在可以发送给多客户端
     *
     * @param: [userName, message] (接收人,发送消息)
     * @return: void ()
     */
    public void sendTextMessage(String userName, String message) {
        // 遍历sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在当前用户
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendText(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /**
     * 功能描述: 此为单点消息 (发送文本) 现在可以发送给多客户端
     *
     * @param: [userName, message] (接收人,发送消息)
     * @return: void ()
     */
    public void sendObjMessage(String userName, Object message) {
        // 遍历sessionPool
        for (String key : sessionPool.keySet()) {
            // 存在当前用户
            if (key.toString().indexOf(userName) != -1) {
                Session session = sessionPool.get(key);
                if (session != null && session.isOpen()) {
                    try {
                        session.getAsyncRemote().sendObject(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

发送信息

@RestController
@RequestMapping("websocket")
public class WebSocketController {
    @GetMapping("setMessage")
    @ApiOperation(value = "发送信息接口", notes = "发送信息接口")
    public Result
        webSocket(@ApiParam(name = "定时任务日志实体", value = "定时任务日志实体", required = false) @RequestBody MessageVO messageVO) {
        Result result = new Result();
        String userName = messageVO.getUserName();
        String message = messageVO.getMessage();
        WebSocket webSocket = new WebSocket();
        webSocket.sendTextMessage(userName, message);
        return result;
    }
}

前段代码

import sysConfig from "../config";
import {Notification} from 'element-ui';
import {EVENT_TYPE} from "../const";
export function openSocket(userId) {
  let ws = new WebSocket(`${sysConfig.SOCKET_URL}/${userId}`);
  // let ws = new WebSocket(`ws://121.40.165.18:8800`);
  ws.onopen = function (evt) {
    Notification({
      title: '欢迎回来!',
      message: `${sysConfig.SOCKET_URL}/${userId}`
    });
  };
  ws.onmessage = function (e) {
    console.log(typeof e.data);
    try{
      if(e.data!=undefined || e.data!=null){
        let json= JSON.parse(e.data);
        Notification({
          title: json.messageTitle,
          message: json.messageText
        });
        //通知页面更新
        window.postMessage(EVENT_TYPE.updateMessage,'/');
      }
    }catch(err){
        console.log("webSocke异常,异常信息:"+err)
    }
    //ws.close();
  };
  ws.onclose = function (evt) {
    console.log('Connection closed.');
  };
}


相关文章
|
17天前
|
消息中间件 Java Kafka
Springboot集成高低版本kafka
Springboot集成高低版本kafka
|
23天前
|
NoSQL Java Redis
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
SpringBoot集成Redis解决表单重复提交接口幂等(亲测可用)
246 0
|
2月前
使用uniapp实现websocket聊天功能
使用uniapp实现websocket聊天功能
|
28天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
394 0
|
1月前
|
NoSQL Java Redis
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
小白版的springboot中集成mqtt服务(超级无敌详细),实现不了掐我头!!!
264 1
|
1月前
|
XML Java 关系型数据库
【SpringBoot系列】SpringBoot集成Fast Mybatis
【SpringBoot系列】SpringBoot集成Fast Mybatis
|
2月前
|
Java
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
【极问系列】springBoot集成elasticsearch出现Unable to parse response body for Response
|
2天前
|
Java 关系型数据库 数据库
【SpringBoot系列】微服务集成Flyway
【4月更文挑战第7天】SpringBoot微服务集成Flyway
【SpringBoot系列】微服务集成Flyway
|
17天前
|
SQL Java 调度
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
SpringBoot集成quartz定时任务trigger_state状态ERROR解决办法
|
24天前
|
NoSQL Java Redis
SpringBoot集成Redis
SpringBoot集成Redis
53 1