package com.walker.tcp.support; import com.walker.infrastructure.utils.StringUtils; import com.walker.tcp.Connection; import com.walker.tcp.ConnectionCache; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 基于内存实现的连接缓存定义。 * @date 2023-09-19 */ public class MemoryConnectionCache implements ConnectionCache { // 连接缓存,key = sessionId, value = Connection private final Map cached = new ConcurrentHashMap<>(128); // 通道ID与绑定用户名称的对应关系,key = 绑定业务名称,value = 通道ID private Map idNameCached = new ConcurrentHashMap<>(128); @Override public void putConnection(Connection connection) { String id = connection.getId(); if(StringUtils.isEmpty(id)){ throw new IllegalArgumentException("connection id 必须存在"); } cached.put(id, connection); idNameCached.put(connection.getName(), id); } @Override public void removeConnection(String id) { Connection connection = this.cached.get(id); if(connection != null){ this.idNameCached.remove(connection.getName()); // // 2023-10-17,断开物理连接 // 2023-10-18 移除代码,看是否聊天正常(财政厅运维) // connection.disconnect(); } this.cached.remove(id); } @Override public void removeConnection(String id, Connection connection) { if(connection == null){ connection = this.cached.get(id); } if(connection != null){ this.idNameCached.remove(connection.getName()); // // 2023-10-17,断开物理连接 // 2023-10-18 移除代码,看是否聊天正常(财政厅运维) // connection.disconnect(); } this.cached.remove(id); } @Override public void updateConnection(Connection connection) { this.cached.put(connection.getId(), connection); } @Override public Connection getConnection(String id) { return this.cached.get(id); } @Override public Connection getConnectionByName(String name) { String id = this.idNameCached.get(name); if(StringUtils.isEmpty(id)){ return null; } return this.cached.get(id); } @Override public String getIdByName(String name) { return this.idNameCached.get(name); } @Override public List getAllConnectionList() { List result = new ArrayList<>(); for(Connection conn : cached.values()){ result.add(conn); } return result; } @Override public List getAllConnectionListBy(int engineId) { List result = new ArrayList<>(); for(Connection conn : cached.values()){ if(conn.getEngineId() == engineId){ result.add(conn); } } return result; } }