首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

物件池化模式實戰:Apache Commons Pool 與 JedisPool 源碼深度剖析

     編輯:Java 綜合教學

物件池化模式實戰:Apache Commons Pool 與 JedisPool 源碼深度剖析

池化核心價值

針對建立成本高(資料庫連線、執行緒、網路連線)的物件,透過復用降低 GC 壓力、提升響應速度。

Commons Pool 核心介面

  • PooledObject<T>:被池化物件包裝,附帶建立時間、狀態、最後使用時間等元資料
  • PooledObjectFactory<T>:物件全生命週期工廠(建立、驗證、銷毀、鈍化/活化)
  • ObjectPool<T>:池介面,提供 borrowObject()/returnObject()
  • GenericObjectPool<T>:標準實現,含驅逐策略、最大/最小閒置、等待超時等

JedisPool 實現剖析

1. JedisFactory(實現 PooledObjectFactory<Jedis>)

public PooledObject makeObject() {
    Jedis jedis = new Jedis(host, port, timeout, ...);
    jedis.connect();
    if (password != null) jedis.auth(password);
    if (database != 0) jedis.select(database);
    return new DefaultPooledObject<>(jedis);
}

public boolean validateObject(PooledObject p) {
    Jedis jedis = p.getObject();
    return jedis.isConnected() && "PONG".equals(jedis.ping());
}

public void destroyObject(PooledObject p) {
    Jedis jedis = p.getObject();
    if (jedis.isConnected()) {
        jedis.quit();
        jedis.disconnect();
    }
}

2. Pool 基類(裝飾器模式包裝 GenericObjectPool)

public abstract class Pool implements Closeable {
    protected GenericObjectPool internalPool;
    
    public Pool(GenericObjectPoolConfig config, PooledObjectFactory factory) {
        this.internalPool = new GenericObjectPool<>(factory, config);
    }
    
    public T getResource() {
        try { return internalPool.borrowObject(); }
        catch (NoSuchElementException e) { throw new JedisException("Pool exhausted", e); }
        catch (Exception e) { throw new JedisConnectionException("Get resource failed", e); }
    }
    
    public void returnResource(T resource) {
        if (resource != null) internalPool.returnObject(resource);
    }
}

3. JedisPoolConfig(預設優化參數)


public JedisPoolConfig() {
    setTestWhileIdle(true);           // 空閒驗證
    setMinEvictableIdleTimeMillis(60000);
    setTimeBetweenEvictionRunsMillis(30000);
    setNumTestsPerEvictionRun(-1);    // 全檢
}

使用範例


JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(500);
config.setMaxIdle(5);
config.setMaxWaitMillis(30000);
config.setTestOnBorrow(true);

JedisPool pool = new JedisPool(config, "192.168.2.191", 8888);
Jedis jedis = pool.getResource();
try { String val = jedis.get("key"); }
finally { pool.returnResource(jedis); } // 或 try-with-resources (Jedis 3.0+)

設計模式亮點

  • 工廠模式分離物件建立邏輯
  • 裝飾器模式靈活擴充池功能
  • 模板方法在 GenericObjectPool 定義生命週期骨架

掌握池化原理有助於自定義資源池(如 HTTP 客戶端、資料庫連線池)並排查洩漏、超時等問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved