背景
在我们实际开发中,存在一些对象,其创建和初始化所需资源较大,比如jdbc连接、redis连接等,然而在使用这些对象时,若不采用一定的优化技术,在服务在高并发情况下会造成服务性能瓶颈。笔者之前在工作中接手的一个RTB系统,由于该系统在操作redis时每次都需创建一个redis连接,导致在服务的QPS达到一定的量级后,通过观察redis服务的连接监控,发现存在大量的新建连接数,增加redis服务端的CPU负载,造成redis查询耗时增加,笔者对redis连接进行池化优化处理,通过一个指定的数量连接池管理redis连接,当每次需操作redis是,则从该连接池中获取一个空闲的redis连接,待操作完成后再归还该连接,期间无需重新建立/断开redis连接,减少了不必要的网络连接和端口的消耗。
commons-pool2 池化功能
笔者使用的apache开源的一款优秀的对象池管理组件apache-commons-pool2,commons-pool2中主要的核心类主要有:GenericObjectPool、PooledObjectFactory、GenericObjectPoolConfig等。
- GenericObjectPool类实现了对象池的管理,在实际使用中,需要指定GenericObjectPoolConfig类和PoolObjectFactory接口实现类,其核心方法有:borrowObject和returnObject,borrowObject方法用于从连接池中获取一个池化对象,returnObject方法用于归还池化对象,其源码如下:
```java
/* @param borrowMaxWaitMillis The time to wait in milliseconds for an object
* to become available
*
* @return object instance from the pool
*
* @throws NoSuchElementException if an instance cannot be returned
*
* @throws Exception if an object instance cannot be returned due to an
* error
*/
public T borrowObject(final long borrowMaxWaitMillis) throws Exception
/**
* {@inheritDoc}
* <p>
* If {@link #getMaxIdle() maxIdle} is set to a positive value and the
* number of idle instances has reached this value, the returning instance
* is destroyed.
* </p>
* <p>
* If {@link #getTestOnReturn() testOnReturn} == true, the returning
* instance is validated before being returned to the idle instance pool. In
* this case, if validation fails, the instance is destroyed.
* </p>
* <p>
* Exceptions encountered destroying objects for any reason are swallowed
* but notified via a {@link SwallowedExceptionListener}.
* </p>
*/
@Override
public void returnObject(final T obj)
```
- PoolObjectFactory接口用于使用者实现该接口创建自定义的PoolObject对象,该工厂接口用于使用者根据具体业务创建和管理池化对戏,其源码如下
```java