最近有个需求,需要实时统计在线的人数,由于该项目并没用到实时通信,也只有这里需要实时统计在线,没必要再搭建一套实时通信服务,所以直接整合的Spring Websocket
。下面的demo
是项目中的简化版,使用Spring Boot
搭建的环境。效果如图所示:
网上对Websocket
的讲解有很多了,这里就不在赘述。简单粗暴,直接开干。
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.56version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
dependencies>
先写一个工具类,用来处理在线人数的统计以及WebSocketSession
的管理
/**
* @Author: Xiuming Lee
* @Describe: 统计人数相关工具类
*/
@Slf4j
public class WebSocketCountUtil {
/**
* 静态变量,用来记录当前在线连接数。即返回前台的人数。
*/
private static Long onlineCount = 0L;
/**
* 用来存放普通用户ID。
*/
private static CopyOnWriteArraySet<String> userIdSet = new CopyOnWriteArraySet<>();
/**
* 用来存放普通用户Session和id。
*/
private static CopyOnWriteArraySet<SessionEntity> usersSessionEntitySet = new CopyOnWriteArraySet<>();
/**
* 用来存放管理员Session和id。
*/
private static CopyOnWriteArraySet<SessionEntity> adminSessionEntitySet = new CopyOnWriteArraySet<>();
/**
* 在线人数增加
*/
public static void onlineCountAdd(WebSocketSession session, String userId) {
userIdSet.add(userId);
SessionEntity sessionEntity = new SessionEntity(userId, session);
usersSessionEntitySet.add(sessionEntity);
onlineCountChangeIf();
}
/**
* 在线人数减少
*/
public static void onlineCountReduce(WebSocketSession session) {
usersSessionEntitySet.forEach(sessionEntity -> {
if (sessionEntity.getSession().getId().equals(session.getId())) {
usersSessionEntitySet.remove(sessionEntity);
userIdSet.remove(sessionEntity.getUserId());
onlineCountChangeIf();
}
});
}
/**
* admin用户增加
*/
public static void adminSessionAdd(WebSocketSession session, String adminUserId) {
SessionEntity sessionEntity = new SessionEntity(adminUserId, session);
adminSessionEntitySet.add(sessionEntity);
}
/**
* admin用户减少
*/
public static void adminSessionReduce(WebSocketSession session) {
log.info("admin用户减少");
log.info(adminSessionEntitySet.toString());
adminSessionEntitySet.forEach(sessionEntity -> {
if (sessionEntity.getSession().getId().equals(session.getId())) {
adminSessionEntitySet.remove(sessionEntity);
log.info(adminSessionEntitySet.toString());
}
});
}
/**
* 向admin推送消息
*/
public static void setMessageToAdmin() {
adminSessionEntitySet.forEach(sessionEntity -> {
MessageEntity messageEntity = new MessageEntity("2", String.valueOf(getOnlineCount()));
String messageString = JSONObject.toJSONString(messageEntity);
try {
sessionEntity.getSession().sendMessage(new TextMessage(messageString));
} catch (IOException e) {
e.printStackTrace();
log.error("发送信息失败-->{}", e.getMessage());
}
});
}
public static Long getOnlineCount() {
return onlineCount;
}
/**
* 在线人数是否改变
*/
private static void onlineCountChangeIf() {
Long size = Long.valueOf(userIdSet.size());
if (onlineCount.equals(size)) {
// 在线人数没有变
return;
}
// 在线人数变了
onlineCount = size;
// 向admin发送消息
setMessageToAdmin();
}
}
WebSocketHandler
是消息和生命周期事件的处理程序。下面编写了两个WebSocketHandler
分别处理普通用户的连接和管理员的连接。
/**
* @Author: Xiuming Lee
* @Describe: 普通用户登录成功后,连接websocket处理的Handler
*/
@Slf4j
public class UserConnectionHandler implements WebSocketHandler {
/**
* 建立连接后触发的回调
*/
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.warn("用户连接成功->{}",session);
}
/**
* 收到消息时触发的回调
*/
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
TextMessage textMessage = (TextMessage)message;
log.warn("收到消息->{}",textMessage);
MessageEntity messageEntity = JSONObject.parseObject(textMessage.getPayload(), MessageEntity.class);
WebSocketCountUtil.onlineCountAdd(session,messageEntity.getContent());
}
/**
* 传输消息出错时触发的回调
*/
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("传输消息出错"+"afterConnectionClosed");
System.out.println(session);
}
/**
* 断开连接后触发的回调
*/
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
log.warn("断开连接->{}",session);
WebSocketCountUtil.onlineCountReduce(session);
}
/**
* 是否处理分片消息
*/
@Override
public boolean supportsPartialMessages() {
return false;
}
}
/**
* @Author: Xiuming Lee
* @Describe: 管理员连接处理的Handler,管理员查看实时用户情况
*/
@Slf4j
public class AdminConnectionHandler implements WebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
log.warn("管理员连接成功->{}",session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
TextMessage textMessage = (TextMessage)message;
log.warn("收到消息->{}",textMessage);
System.out.println(session);
MessageEntity messageEntity = JSONObject.parseObject(textMessage.getPayload(), MessageEntity.class);
WebSocketCountUtil.adminSessionAdd(session,messageEntity.getContent());
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
System.out.println("传输消息出错"+"afterConnectionClosed");
System.out.println(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
log.warn("管理员断开连接->{}",session);
WebSocketCountUtil.adminSessionReduce(session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
/**
* @Author: Xiuming Lee
* @Describe:WebSocket配置文件
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new UserConnectionHandler(),"/ws/userCount") // 普通用户websocket的连接路径
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOrigins("*");
registry.addHandler(new AdminConnectionHandler(),"/ws/admin") // 管理员websocket的连接路径
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setAllowedOrigins("*");
}
/**
* 以下是配置WebSocket的配置属性,例如消息缓冲区大小,空闲超时等。
* @return
*/
@Bean
public ServletServerContainerFactoryBean createWebSocketContainer() {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setMaxTextMessageBufferSize(8192);
container.setMaxBinaryMessageBufferSize(8192);
container.setMaxSessionIdleTimeout(300000L);
return container;
}
}
以上核心代码已贴出,完整代码参考GitHub源码。