浅谈轻量级socket连接池实现

简介: 浅谈轻量级socket连接池实现

1.背景

前段时间有幸参与到开源轻量级分布式文件系统Fastdfs Java-SDK的改造,


支持连接池和短连接两种方式,是否开启连接池可选(默认开启),短连接(用完即关闭)


2.如何实现

调研了连接池下,网上很多socket连接池都是用Apache Commons Pool来实现的,个人感觉可能有点重,所以就完全原生代码实现连接池开发了。


3.实现代码

·socket连接类

public class Connection {
  private Socket sock;
  private InetSocketAddress inetSockAddr;
  private Long lastAccessTime = System.currentTimeMillis();
  private boolean needActiveTest = false;
  public Connection(Socket sock, InetSocketAddress inetSockAddr) {
      this.sock = sock;
      this.inetSockAddr = inetSockAddr;
  }
  /**
   * get the server info
   *
   * @return the server info
   */
  public InetSocketAddress getInetSocketAddress() {
      return this.inetSockAddr;
  }
  public OutputStream getOutputStream() throws IOException {
      return this.sock.getOutputStream();
  }
  public InputStream getInputStream() throws IOException {
      return this.sock.getInputStream();
  }
  public Long getLastAccessTime() {
      return lastAccessTime;
  }
  public void setLastAccessTime(Long lastAccessTime) {
      this.lastAccessTime = lastAccessTime;
  }
  /**
   *
   * @throws IOException
   */
  public void close() throws IOException {
      //if connection enabled get from connection pool
      if (ClientGlobal.g_connection_pool_enabled) {
          ConnectionPool.closeConnection(this);
      } else {
          this.closeDirectly();
      }
  }
  public void release() throws IOException {
      if (ClientGlobal.g_connection_pool_enabled) {
          ConnectionPool.releaseConnection(this);
      } else {
          this.closeDirectly();
      }
  }
  /**
   * force close socket,
   */
  public void closeDirectly() throws IOException {
      if (this.sock != null) {
          try {
              ProtoCommon.closeSocket(this.sock);
          } finally {
              this.sock = null;
          }
      }
  }
  public boolean activeTest() throws IOException {
      if (this.sock == null) {
          return false;
      }
      return ProtoCommon.activeTest(this.sock);
  }
  public boolean isConnected() {
      boolean isConnected = false;
      if (sock != null) {
          if (sock.isConnected()) {
              isConnected = true;
          }
      }
      return isConnected;
  }
  public boolean isAvaliable() {
      if (isConnected()) {
          if (sock.getPort() == 0) {
              return false;
          }
          if (sock.getInetAddress() == null) {
              return false;
          }
          if (sock.getRemoteSocketAddress() == null) {
              return false;
          }
          if (sock.isInputShutdown()) {
              return false;
          }
          if (sock.isOutputShutdown()) {
              return false;
          }
          return true;
      }
      return false;
  }
  public boolean isNeedActiveTest() {
      return needActiveTest;
  }
  public void setNeedActiveTest(boolean needActiveTest) {
      this.needActiveTest = needActiveTest;
  }
}

·连接管理器(主要职责:获取连接,关闭连接,释放连接)

public class ConnectionManager {
    private InetSocketAddress inetSocketAddress;
    /**
     * count of total connections 
     */
    private AtomicInteger totalCount = new AtomicInteger();
    /**
     * count of free connections
     */
    private AtomicInteger freeCount = new AtomicInteger();
    /**
     * lock
     */
    private ReentrantLock lock = new ReentrantLock(true);
    private Condition condition = lock.newCondition();
    /**
     * free container connection  
     */
    private LinkedList<Connection> freeConnections = new LinkedList<Connection>();
    private ConnectionManager() {
    }
    public ConnectionManager(InetSocketAddress socketAddress) {
        this.inetSocketAddress = socketAddress;
    }
   /**
    * get connection
    **/
    public Connection getConnection() throws MyException {
        lock.lock();
        try {
            Connection connection = null;
            while (true) {
                if (freeCount.get() > 0) {
                    freeCount.decrementAndGet();
                    connection = freeConnections.poll();
                    if (!connection.isAvaliable() || (System.currentTimeMillis() - connection.getLastAccessTime()) > ClientGlobal.g_connection_pool_max_idle_time) {
                        closeConnection(connection);
                        continue;
                    }
                    if (connection.isNeedActiveTest()) {
                        boolean isActive = false;
                        try {
                            isActive = connection.activeTest();
                        } catch (IOException e) {
                            System.err.println("send to server[" + inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort() + "] active test fail ,emsg:" + e.getMessage());
                            isActive = false;
                        }
                        if (!isActive) {
                            closeConnection(connection);
                            continue;
                        } else {
                            connection.setNeedActiveTest(false);
                        }
                    }
                } else if (ClientGlobal.g_connection_pool_max_count_per_entry == 0 || totalCount.get() < ClientGlobal.g_connection_pool_max_count_per_entry) {
                    connection = ConnectionFactory.create(this.inetSocketAddress);
                    totalCount.incrementAndGet();
                } else {
                    try {
                        if (condition.await(ClientGlobal.g_connection_pool_max_wait_time_in_ms, TimeUnit.MILLISECONDS)) {
                            //wait single success
                            continue;
                        }
                        throw new MyException("connect to server " + inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort() + " fail, wait_time > " + ClientGlobal.g_connection_pool_max_wait_time_in_ms + "ms");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        throw new MyException("connect to server " + inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort() + " fail, emsg:" + e.getMessage());
                    }
                }
                return connection;
            }
        } finally {
            lock.unlock();
        }
    }
   /**
   *release connection
   */
    public void releaseConnection(Connection connection) {
        if (connection == null) {
            return;
        }
        lock.lock();
        try {
            connection.setLastAccessTime(System.currentTimeMillis());
            freeConnections.add(connection);
            freeCount.incrementAndGet();
            condition.signal();
        } finally {
            lock.unlock();
        }
    }
    /**
     *close connection
     *
     */
    public void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                totalCount.decrementAndGet();
                connection.closeDirectly();
            }
        } catch (IOException e) {
            System.err.println("close socket[" + inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort() + "] error ,emsg:" + e.getMessage());
            e.printStackTrace();
        }
    }
    public void setActiveTestFlag() {
        if (freeCount.get() > 0) {
            lock.lock();
            try {
                for (Connection freeConnection : freeConnections) {
                    freeConnection.setNeedActiveTest(true);
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

注:其中setActiveTestFlag()方法解释一下,有可能出现连接断了之后,可能是这台服务器重启了,或者网络抽风导致闪断。希望只牺牲一次请求,主要解决服务器重启问题


大致思路就是一旦client请求时一旦有连接出现IOException,就会将所有当前实例对应的所有连接全部变为

需要activeTest,当下一个连接获取时,就会检测所有的连接,从而达到只牺牲一次请求的目的.

.

·管理器连接池(由于存在多个实例,一个实例对应一个ConnectionManager,连接获取,释放,关闭的入口)

实现代码

public class ConnectionPool {
    /**
     * key is ip:port, value is ConnectionManager
     */
    private final static ConcurrentHashMap<String, ConnectionManager> CP = new ConcurrentHashMap<String, ConnectionManager>();
    public static Connection getConnection(InetSocketAddress socketAddress) throws MyException {
        if (socketAddress == null) {
            return null;
        }
        String key = getKey(socketAddress);
        ConnectionManager connectionManager;
        connectionManager = CP.get(key);
        if (connectionManager == null) {
            synchronized (ConnectionPool.class) {
                connectionManager = CP.get(key);
                if (connectionManager == null) {
                    connectionManager = new ConnectionManager(socketAddress);
                    CP.put(key, connectionManager);
                }
            }
        }
        return connectionManager.getConnection();
    }
    public static void releaseConnection(Connection connection) throws IOException {
        if (connection == null) {
            return;
        }
        String key = getKey(connection.getInetSocketAddress());
        ConnectionManager connectionManager = CP.get(key);
        if (connectionManager != null) {
            connectionManager.releaseConnection(connection);
        } else {
            connection.closeDirectly();
        }
    }
    public static void closeConnection(Connection connection) throws IOException {
        if (connection == null) {
            return;
        }
        String key = getKey(connection.getInetSocketAddress());
        ConnectionManager connectionManager = CP.get(key);
        if (connectionManager != null) {
            connectionManager.closeConnection(connection);
            connectionManager.setActiveTestFlag();
        } else {
            connection.closeDirectly();
        }
    }
    private static String getKey(InetSocketAddress socketAddress) {
        if (socketAddress == null) {
            return null;
        }
        return String.format("%s:%s", socketAddress.getAddress().getHostAddress(), socketAddress.getPort());
 }
相关文章
|
算法
RSA和RSA2签名算法区别
RSA和RSA2签名算法 什么是数字签名? 一个很好的说明文档可以参考:What is a Digital Signature?,中文翻译可以参考:数字签名是什么?. 简单来说,签名主要包含两个过程:摘要和非对称加密,首先对需要签名的数据做摘要(类似于常见的MD5)后得到摘要结果,然后通过签名者的私钥对摘要结果进行非对称加密即可得到签名结果。
7019 12
|
弹性计算 负载均衡 容灾
阿里云渠道商:弹性公网IP和固定公网IP区别在哪?
本文解析弹性公网IP与固定公网IP的核心区别,涵盖资源关系、生命周期、高可用性、成本模式及适用场景。EIP独立灵活,支持动态绑定与容灾切换,适合生产环境;固定IP则绑定实例,适用于简单短期需求。选型建议根据业务重要性与扩展需求决定。
UUID 与 MD5 重复概率深度分析
UUID与MD5均生成128位值,理论碰撞概率相同。但UUIDv4基于随机生成,实际重复概率极低,适合唯一标识;MD5依赖输入数据,存在已知安全漏洞,碰撞风险更高,不推荐用于安全敏感场景。
|
消息中间件 存储 监控
消息队列通信的优缺点
【10月更文挑战第29天】消息队列通信具有诸多优点,如解耦性强、异步通信、缓冲削峰等,能够有效地提高系统的灵活性、可扩展性和稳定性。但同时也存在一些缺点,如系统复杂性增加、性能开销、数据一致性挑战和实时性受限等。在实际应用中,需要根据具体的业务需求和场景,权衡其优缺点,合理地选择和使用消息队列通信机制,以实现系统的高效运行和优化。
|
Java 网络安全 Apache
SshClient应用指南:使用org.apache.sshd库在服务器中执行命令。
总结起来,Apache SSHD库是一个强大的工具,甚至可以用于创建你自己的SSH Server。当你需要在服务器中执行命令时,这无疑是非常有用的。希望这个指南能对你有所帮助,并祝你在使用Apache SSHD库中有一个愉快的旅程!
1177 29
|
缓存 Java API
基于Spring Boot REST API设计指南
【10月更文挑战第11天】 在构建现代Web应用程序时,RESTful API已成为一种标准,使得不同的应用程序能够通过HTTP协议进行通信,实现资源的创建、读取、更新和删除等操作。Spring Boot作为一个功能强大的框架,能够轻松创建RESTful API。本文将详细介绍如何在Spring Boot中设计和实现高质量的RESTful API。
803 61
|
存储 XML Java
Android 文件数据储存之内部储存 + 外部储存
简介:本文详细介绍了Android内部存储与外部存储的使用方法及核心原理。内部存储位于手机内存中,默认私有,适合存储SharedPreferences、SQLite数据库等重要数据,应用卸载后数据会被清除。外部存储包括公共文件和私有文件,支持SD卡或内部不可移除存储,需申请权限访问。文章通过代码示例展示了如何保存、读取、追加、删除文件以及将图片保存到系统相册的操作,帮助开发者理解存储机制并实现相关功能。
3416 2
|
容器 安全 Docker
浅谈容器逃逸
【6月更文挑战第2天】容器逃逸是严重的安全风险,威胁云计算系统的安全。
|
Java API 容器
理解HTTP协议中的multipart/form-data
之前在写一个通用HTTP组件的时候遇到过媒体(Media)类型multipart/form-data的封装问题,这篇文章主要简单介绍一下HTTP协议中媒体类型multipart/form-data的定义、应用和简单实现。
2265 0
理解HTTP协议中的multipart/form-data
|
Web App开发
Signature length not correct: got 128 but was expecting 256和 got 256 but was expecting 128-自查方案
说明:     以下错误是支付宝公钥(alipay_public_key)与签名类型(sign_type)不匹配导致    Signature length not correct: got 128 but was expecting 256(签名长度不正确:得到128,但预期为256)    S...
13113 3