聊聊LettucePoolingConnectionProvider

本文主要研究一下LettucePoolingConnectionProviderjava

LettucePoolingConnectionProvider

spring-data-redis-2.0.10.RELEASE-sources.jar!/org/springframework/data/redis/connection/lettuce/LettucePoolingConnectionProvider.javagit

/**
 * {@link LettuceConnectionProvider} with connection pooling support. This connection provider holds multiple pools (one
 * per connection type) for contextualized connection allocation.
 * <p />
 * Each allocated connection is tracked and to be returned into the pool which created the connection. Instances of this
 * class require {@link #destroy() disposal} to de-allocate lingering connections that were not returned to the pool and
 * to close the pools.
 *
 * @author Mark Paluch
 * @author Christoph Strobl
 * @since 2.0
 * @see #getConnection(Class)
 */
class LettucePoolingConnectionProvider implements LettuceConnectionProvider, RedisClientProvider, DisposableBean {

    private final static Log log = LogFactory.getLog(LettucePoolingConnectionProvider.class);

    private final LettuceConnectionProvider connectionProvider;
    private final GenericObjectPoolConfig poolConfig;
    private final Map<StatefulConnection<?, ?>, GenericObjectPool<StatefulConnection<?, ?>>> poolRef = new ConcurrentHashMap<>(
            32);
    private final Map<Class<?>, GenericObjectPool<StatefulConnection<?, ?>>> pools = new ConcurrentHashMap<>(32);

    LettucePoolingConnectionProvider(LettuceConnectionProvider connectionProvider,
            LettucePoolingClientConfiguration clientConfiguration) {

        Assert.notNull(connectionProvider, "ConnectionProvider must not be null!");
        Assert.notNull(clientConfiguration, "ClientConfiguration must not be null!");

        this.connectionProvider = connectionProvider;
        this.poolConfig = clientConfiguration.getPoolConfig();
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.connection.lettuce.LettuceConnectionProvider#getConnection(java.lang.Class)
     */
    @Override
    public <T extends StatefulConnection<?, ?>> T getConnection(Class<T> connectionType) {

        GenericObjectPool<StatefulConnection<?, ?>> pool = pools.computeIfAbsent(connectionType, poolType -> {
            return ConnectionPoolSupport.createGenericObjectPool(() -> connectionProvider.getConnection(connectionType),
                    poolConfig, false);
        });

        try {

            StatefulConnection<?, ?> connection = pool.borrowObject();

            poolRef.put(connection, pool);

            return connectionType.cast(connection);
        } catch (Exception e) {
            throw new PoolException("Could not get a resource from the pool", e);
        }
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.connection.lettuce.RedisClientProvider#getRedisClient()
     */
    @Override
    public AbstractRedisClient getRedisClient() {

        if (connectionProvider instanceof RedisClientProvider) {
            return ((RedisClientProvider) connectionProvider).getRedisClient();
        }

        throw new IllegalStateException(
                String.format("Underlying connection provider %s does not implement RedisClientProvider!",
                        connectionProvider.getClass().getName()));
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.data.redis.connection.lettuce.LettuceConnectionProvider#release(io.lettuce.core.api.StatefulConnection)
     */
    @Override
    public void release(StatefulConnection<?, ?> connection) {

        GenericObjectPool<StatefulConnection<?, ?>> pool = poolRef.remove(connection);

        if (pool == null) {
            throw new PoolException("Returned connection " + connection
                    + " was either previously returned or does not belong to this connection provider");
        }

        pool.returnObject(connection);
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.beans.factory.DisposableBean#destroy()
     */
    @Override
    public void destroy() throws Exception {

        if (!poolRef.isEmpty()) {

            log.warn("LettucePoolingConnectionProvider contains unreleased connections");

            poolRef.forEach((connection, pool) -> pool.returnObject(connection));
            poolRef.clear();
        }

        pools.forEach((type, pool) -> pool.close());
        pools.clear();
    }
}
  • 這個provider與普通的鏈接不一樣,它區分了不一樣類型的鏈接池,於是pools是map結構的,並且還多了poolRef這個map來維護每一個鏈接所在鏈接池
  • pools主要是用於根據鏈接類型獲取對應鏈接池,用於鏈接的借用場景,而poolRef主要是用於鏈接的歸還場景
  • 這裏採用了ConcurrentHashMap的computeIfAbsent方法,對於key不存在的則觸發建立並返回,對於key存在的則直接返回

小結

  • lettuce 4.0版本引入了StatefulConnection,它會維護登陸、事務、所選數據庫,讀寫等狀態
  • StatefulConnection有幾個類型,分別是StatefulRedisConnection(StatefulRedisPubSubConnection、StatefulRedisMasterSlaveConnection)、StatefulRedisSentinelConnection、StatefulRedisClusterConnection
  • LettucePoolingConnectionProvider維護了多類型的鏈接的鏈接池,於是採用map的數據結構,否則單一類型的鏈接直接使用GenericObjectPool便可

doc

相關文章
相關標籤/搜索