websocket在线用户管理+消息的推送+心跳检测

1.maven依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2.配置类

/**
 * 开启WebSocket
 * WebScoket配置
 * 通过这个配置 spring boot 才能去扫描后面的关于 websocket 的注解
 */
@Configuration
public class WebSocketConfig {

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

}

3.demo

@Component
@Slf4j
//访问路径 ws://localhost:8081/websocketdemo?userId=1
@ServerEndpoint(value = "/websocketdemo")
public class Demo {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static final AtomicInteger currentOnlineNumber = new AtomicInteger();
    //消息存储
    private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen //收到socket请求触发
    public void onOpen(Session session) throws IOException {
        //获取传递的参数userId
        String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
        currentOnlineNumber.incrementAndGet(); //当前在线数量+1
        sessionPool.put(userId, session);//session存储
        log.info("用户:___" + userId + "___成功连接,当前在线用户___" + currentOnlineNumber);
    }

    @OnClose//关闭socket请求触发
    public void onClose(Session session) {
        //获取传递的参数userId
        String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
        currentOnlineNumber.decrementAndGet();//当前在线数量-1
        sessionPool.remove(userId);//session删除
        log.info("用户:___" + userId + "___断开连接,当前在线用户在线人数___" + currentOnlineNumber);

    }

    @OnMessage//收到socket请求触发(用于心跳检测)
    public void OnMessage(Session session, String message) throws IOException {
        //获取传递的参数userId
        String userId = session.getRequestParameterMap().get("userId").toString().replaceAll("\\[|\\]", "");
        log.info("收到___" + userId + "___推送消息" + message);
        if (ObjectUtil.isEmpty(message) && message.contains("ping")) {
            sessionPool.get(userId).getBasicRemote().sendText(JSON.toJSONString("pong"));
        }
        //推送消息给用户
        HashMap<String, Object> mapq = new HashMap<>();
        mapq.put("1", "2");
        mapq.put("3 ", "4");
        this.onMessagePush(userId, mapq);
    }

    /**
     * 给指定用户推送消息
     *
     * @param userId
     * @throws IOException
     */
    public <T> void onMessagePush(String userId, T t) throws IOException {
        log.info(t.toString());
        sessionPool.get(userId).getBasicRemote().sendText(JSON.toJSONString("notice|" + t));
    }
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值