SpringBoot2.0集成websocket,实现服务端主动推送消息到客户端

本文介绍了如何在SpringBoot2.0项目中集成WebSocket,通过详细步骤包括引入依赖、启用支持、编写服务类以及实现服务端主动向客户端推送消息。同时提供了客户端示例,帮助理解整个流程。
摘要由CSDN通过智能技术生成

SpringBoot2.0集成websocket,实现服务端主动推送消息到客户端

引入WebSocket依赖

maven

<dependency>  
    <groupId>org.springframework.boot</groupId>  
   <artifactId>spring-boot-starter-websocket</artifactId>  
</dependency> 

gradle

implementation 'org.springframework.boot:spring-boot-starter-websocket'

启用websocket的支持

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


@Configuration
public class WebSocketConfig {
   

    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
   
        return new ServerEndpointExporter();
    }

}

编写websocket服务类



import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 
 * 集群环境下的示例
 * 用户标识与服务器ip绑定,存储在redis中
 * 心跳机制:客户端发送心跳包,服务端回应,客户端根据回应情况做操作
 **/
@ServerEndpoint("/WebSocketServer/{userId}/{deviceType}")
@Component
public class WebSocketServer {
   

    static Log log = LogFactory.get(WebSocketServer.class);
    /**
     * 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Map,用来存放每个客户端对应的session对象。
     */
    private static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收userId
     */
    private String userId = "";

    /**
     * 存储用户关联的接收端类型  接收端 
     */
//    private String deviceType = "";

    private static ConcurrentHashMap<String, String> deviceTypeMap = new ConcurrentHashMap<>();

    private final String PING = "ping";
    private final String PONG = "pong";


    public static final String ACCEPTOR_TYPE_PC_INT = "1";
    public static final String ACCEPTOR_TYPE_PDA_INT = "2";
    private StringRedisTemplate stringRedisTemplate = SpringUtils.getBean(StringRedisTemplate.class);


    private final String localIP = GetLocalAddress.getLocalIp();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId, @PathParam("deviceType") String deviceType) {
   

        this.session = session;
        this.userId = userId;

        //处理旧信息
        if (clients.containsKey(userId)) {
   
            getOldSession(userId);
        }
        //本地存储
        clients.put(userId, session);
        deviceTypeMap.put(userId, deviceType);
        //redis存储用户id与本地ip关联数据
        saveServerIpToRedis(userId, deviceType);

        log.info("ip:" + localIP + " 用户连接:" + userId + ",所在设备端:" + deviceType);

        try {
   
            sendMessage("ip:" + localIP + "用户" + userId + " 连接成功", this.userId);
        } catch (Exception e) {
   
            log.error("ip:" + localIP + " 用户:" + userId + ",网络异常!!!!!!");
        }
    }

    private void saveServerIpToRedis(String userId, String deviceType) {
   
        if (StringUtils.isNotBlank(userId
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值