详解java中的对象池池化功能

本文介绍了Java中使用commons-pool2进行对象池化,特别是针对资源消耗大的对象如JDBC连接和Redis连接。通过创建连接池管理Redis连接,减少网络消耗和CPU负载,提升服务性能。示例中详细讲解了如何利用GenericObjectPool、PooledObjectFactory和GenericObjectPoolConfig来实现对象池,并给出了Jedis连接池的配置和测试代码。
摘要由CSDN通过智能技术生成

 背景


在我们实际开发中,存在一些对象,其创建和初始化所需资源较大,比如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)

```

  1.  PoolObjectFactory接口用于使用者实现该接口创建自定义的PoolObject对象,该工厂接口用于使用者根据具体业务创建和管理池化对戏,其源码如下

```java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值