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