Lettuce链接池

       Lettuce 链接被设计为线程安全,因此一个链接能够被多个线程共享,同时lettuce链接默认是自动重连.虽然链接池在大多数状况下是没必要要的,但在某些用例中多是有用的.lettuce提供通用的链接池支持. 若有疏漏后续会更新 https://www.cnblogs.com/wei-zw/p/9163687.htmlhtml

链接池是否有必要?java


     Lettuce被线程安全的,它知足了多数场景需求. 全部Redis用户的操做是单线程执行的.使用多链接并不能改善一个应用的性能. 阻塞操做的使用一般与得到专用链接的工做线程结合在一块儿.
        使用Redis事务是使用动态链接池的典型场景,由于须要专用链接的线程数趋于动态.也就是说,动态链接池的需求是有限的.链接池老是伴随着复杂性和维护成本提高.react

同步链接池apache

  使用命令式编程,同步链接池是正确的选择,由于它在用于执行执行Redis命令的线程上执行全部操做.编程

   前提条件
       Lettuce须要依赖 Apache的 common-pool2(至少是2.2)提供链接池. 确认在你的classpath下包含这个依赖.不然你就不能使用链接池.
若是使用Maven,向你的pom.xml添加以下依赖缓存

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.3</version>
</dependency>

 链接池支持安全

Lettuce提供通用链接池支持,它须要一个用于建立任何支持类型链接(单个,发布订阅,哨兵,主从,集群)的提供者. ConnectionPoolSupport 将根据你的需求建立一个 GenericObjectPool或SoftReferenceObjectPool. 链接池能够分配包装类型或直接链接async

  • 包装实例在调用StatefulConnection.close()时,会将链接归还到链接池
  • 直接链接须要调用GenericObjectPool.returnObject(...)归还到链接池

基本用法:ide

  包装链接源码分析

  GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(2);

        GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport.createGenericObjectPool(
                () -> client.connect(), poolConfig);
        for (int i = 0; i < 10; i++) {
            StatefulRedisConnection<String, String> connection = pool.borrowObject();
            RedisCommands<String, String> sync = connection.sync();
            sync.ping();
            connection.close();
        }

 

直接链接

     GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport.createGenericObjectPool(
                () -> client.connect(), new GenericObjectPoolConfig(), false);

        for (int i = 0; i < 10; i++) {
            StatefulRedisConnection<String, String> connection = pool.borrowObject();
            RedisCommands<String, String> sync = connection.sync();
            sync.ping();
       //主动将链接归还到链接池  pool.returnObject(connection); }

  

相关源码分析

 public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
            Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

        LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
        LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");

        AtomicReference<ObjectPool<T>> poolRef = new AtomicReference<>();

        GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<T>(connectionSupplier), config) {

            @Override
            public T borrowObject() throws Exception {
                //若是wrapConnection 设置为true,则对链接建立动态代理
                return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
            }

            @Override
            public void returnObject(T obj) {

                if (wrapConnections && obj instanceof HasTargetConnection) {
                    super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                    return;
                }
                super.returnObject(obj);
            }
        };

        poolRef.set(pool);

        return pool;
    }

  建立一个包装类型到链接

 private static <T> T wrapConnection(T connection, ObjectPool<T> pool) {
        
        //建立调用处理器
        ReturnObjectOnCloseInvocationHandler<T> handler = new ReturnObjectOnCloseInvocationHandler<T>(connection, pool);

        Class<?>[] implementedInterfaces = connection.getClass().getInterfaces();
        Class[] interfaces = new Class[implementedInterfaces.length + 1];
        interfaces[0] = HasTargetConnection.class;
        System.arraycopy(implementedInterfaces, 0, interfaces, 1, implementedInterfaces.length);
        //建立代理链接
        T proxiedConnection = (T) Proxy.newProxyInstance(connection.getClass().getClassLoader(), interfaces, handler);
        //向链接调用处理器设置代理链接
        handler.setProxiedConnection(proxiedConnection);
        //返回代理链接
        return proxiedConnection;
    }

  包装类型链接的动态调用处理器

  private static class ReturnObjectOnCloseInvocationHandler<T> extends AbstractInvocationHandler {
        //被代理对链接
        private T connection;
        private T proxiedConnection;
        private Map<Method, Object> connectionProxies = new ConcurrentHashMap<>(5, 1);
        //链接池
        private final ObjectPool<T> pool;

        ReturnObjectOnCloseInvocationHandler(T connection, ObjectPool<T> pool) {
            this.connection = connection;
            this.pool = pool;
        }
        
        //设置代理链接
        void setProxiedConnection(T proxiedConnection) {
            this.proxiedConnection = proxiedConnection;
        }

        @Override
        protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
             //若是调用方法是  getStatefulConnection则返回代理链接
            if (method.getName().equals("getStatefulConnection")) {
                return proxiedConnection;
            }
            //若是调用的方法是getTargetConnection 则返回真实链接
            if (method.getName().equals("getTargetConnection")) {
                return connection;
            }
            //若是真实链接为null则抛出异常
            if (connection == null) {
                throw new RedisException("Connection is deallocated and cannot be used anymore.");
            }
            //若是调用的方法是close则将代理链接归还到链接池,并将真实链接设置和代理链接设置为null
            if (method.getName().equals("close")) {
                pool.returnObject(proxiedConnection);
                connection = null;
                proxiedConnection = null;
                connectionProxies.clear();
                return null;
            }

            try {
                //若是调用方法是获取链接则从代理链接池中获取,若是没有则建立代理链接并放入缓存
                if (method.getName().equals("sync") || method.getName().equals("async") || method.getName().equals("reactive")) {
                    return connectionProxies.computeIfAbsent(
                            method, m -> getInnerProxy(method, args));
                }
                //其它方法不在多任何拦截
                return method.invoke(connection, args);

            } catch (InvocationTargetException e) {
                throw e.getTargetException();
            }
        }

        @SuppressWarnings("unchecked")
        private Object getInnerProxy(Method method, Object[] args) {

            try {
                Object result = method.invoke(connection, args);

                result = Proxy.newProxyInstance(getClass().getClassLoader(), result.getClass().getInterfaces(),
                        new DelegateCloseToConnectionInvocationHandler<>((AutoCloseable) proxiedConnection, result));

                return result;
            } catch (IllegalAccessException e) {
                throw new RedisException(e);
            } catch (InvocationTargetException e) {
                throw new RedisException(e.getTargetException());

            }
        }

        public T getConnection() {
            return connection;
        }
    }
相关文章
相关标签/搜索