SpringCloud微服务整合websocket

本文介绍如何在Spring Boot项目中实现WebSocket功能,包括引入依赖、配置、编写服务端代码及网关配置等步骤。提供了完整的示例代码,便于读者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入相关Jar包

  <!--添加websockert依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

配置Config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

编写Websocket服务



import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;


@Slf4j
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //用户ID 
    private String userId;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新连接加入!当前连接数为" + getOnlineCount());
        //获取用户ID
        getUserId();
        //发送“未读消息”
        sendMessage(getUnreadCountMsg());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭!当前连接数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) {
        try {
            this.session.getBasicRemote().sendText(message);
            log.info("websocket发送消息成功:{}", message);
        } catch (IOException e) {
            log.error("websocket服务端发送消息异常");
            e.printStackTrace();
        }
    }

    /**
     * 自定义方法
     */
    @Async
    public static void sendUnreadCountMsgByUserId(String userId) {
        log.info("------------自定义方法------------,userId:{}", userId);
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        for (WebSocketServer item : webSocketSet) {
            if (userId.equals(item.userId)) {
                item.sendMessage("自定义方法");
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    /**
     * 从url获取入参“userId”
     *
     * @return
     */
    private String getUserId() {
        String userId = getParameterMap().get("userId");

        //如没有传递userId,则关闭连接
        if (StringUtils.isEmpty(userId)) {
            sendMessage("userId不能为空");
            log.error("userId不能为空");
            throw new RuntimeException("userId不能为空");
        }
        this.userId = userId;
        return userId;
    }

   
    private HashMap<String, String> getParameterMap(){
        HashMap<String, String> map = new HashMap<>();

        String queryString = session.getQueryString();
        if(StringUtils.isEmpty(queryString) ){
            return map;
        }

        String[] split = queryString.split("&");
        for (String s : split) {
            if (s.contains("=")) {
                String[] strings = s.split("=");
                map.put(strings[0], strings[1]);
            }
        }
        return map;
    }

}

网关配置

可以通过网关路径连接websocket

spring:
  cloud:
    gateway:
      routes:
         - id: xx-websocket
           uri: lb:ws://xx-websocket
           predicates:
              - Path=/xx/websocket/**

测试地址

http://www.websocket-test.com/

ws://localhost:7900/xxx-cloud/websocket?userId=xxx

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值