Explicación detallada de los parámetros de configuración de GenericObjectPool del grupo de objetos

Explicación detallada de los parámetros de configuración de GenericObjectPool del grupo de objetos

confiar

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

Para utilizar GenericObjectPool , es necesario comprender GenericObjectPoolConfig.Los parámetros de configuración se explicarán a continuación.

1. Parámetros de configuración de la clase principal BaseObjectPoolConfig

/**
 * Provides the implementation for the common attributes shared by the
 * sub-classes. New instances of this class will be created using the defaults
 * defined by the public constants.
 * <p>
 * This class is not thread-safe.
 *  * @since 2.0
 */
public abstract class BaseObjectPoolConfig extends BaseObject implements Cloneable {
    private boolean lifo = DEFAULT_LIFO;

    private boolean fairness = DEFAULT_FAIRNESS;

    private long maxWaitMillis = DEFAULT_MAX_WAIT_MILLIS;

    private long minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;

    private long evictorShutdownTimeoutMillis = DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT_MILLIS;

    private long softMinEvictableIdleTimeMillis = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;

    private int numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;

    private String evictionPolicyClassName = DEFAULT_EVICTION_POLICY_CLASS_NAME;

    private boolean testOnCreate = DEFAULT_TEST_ON_CREATE;

    private boolean testOnBorrow = DEFAULT_TEST_ON_BORROW;

    private boolean testOnReturn = DEFAULT_TEST_ON_RETURN;

    private boolean testWhileIdle = DEFAULT_TEST_WHILE_IDLE;

    private long timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;

    private boolean blockWhenExhausted = DEFAULT_BLOCK_WHEN_EXHAUSTED;

    private boolean jmxEnabled = DEFAULT_JMX_ENABLE;

    private String jmxNamePrefix = DEFAULT_JMX_NAME_PREFIX;

    private String jmxNameBase = DEFAULT_JMX_NAME_BASE;
}
  • lifo
    proporciona grupos con dos modos de comportamiento: último en entrar , primero en salir (LIFO) y primero en entrar, primero en salir (FIFO); el
    valor predeterminado DEFAULT_LIFO = verdadero, cuando hay objetos libres disponibles en el grupo, llamar al método de préstamo de objetos devolverá el más reciente (última en) instancia.
    org.apache.commons.pool2.impl.GenericObjectPool

        if (getLifo()) {
            idleObjects.addFirst(p);
        } else {
            idleObjects.addLast(p);
        }
  • equidad
    Ya sea para usar al adquirir recursos del grupo o devolver recursos al grupo; el mecanismo de bloqueo de equidad de java.util.concurrent.locks.ReentrantLock.ReentrantLock.
    Por defecto DEFAULT_FAIRNESS = false
    org.apache.commons.pool2.impl.GenericObjectPool

    idleObjects = new LinkedBlockingDeque<PooledObject<T>>(config.getFairness());
  • maxWaitMillis
    Cuando se agotan los recursos del grupo de conexiones, el tiempo máximo de espera (unidad: milisegundos) para que la persona que llama obtenga una conexión; el
    valor predeterminado es DEFAULT_MAX_WAIT_MILLIS = -1L, que nunca expirará.
    org.apache.commons.pool2.impl.GenericObjectPool

    @Override
    public T borrowObject() throws Exception {
        return borrowObject(getMaxWaitMillis());
    }
  • minEvictableIdleTimeMillis
    es el tiempo mínimo de inactividad de la conexión. Una vez alcanzado este valor, la conexión inactiva puede eliminarse (dependiendo de si se ha alcanzado el número máximo de conexiones inactivas); el
    valor predeterminado DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L 60L 30L
    org.apache.commons .pool2.impl.GenericObjectPool

    final EvictionConfig evictionConfig = new EvictionConfig(
                        getMinEvictableIdleTimeMillis(),
                        getSoftMinEvictableIdleTimeMillis(),
                        getMinIdle());
  • evictorShutdownTimeoutMillis
    cierra el tiempo de espera del subproceso de desalojo; el
    valor predeterminado DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT_MILLIS = 10L * 1000L
    org.apache.commons.pool2.impl.BaseGenericObjectPool

    final void startEvictor(final long delay) {
        synchronized (evictionLock) {
            if (null != evictor) {
                EvictionTimer.cancel(evictor, evictorShutdownTimeoutMillis, TimeUnit.MILLISECONDS);
                evictor = null;
                evictionIterator = null;
            }
            if (delay > 0) {
                evictor = new Evictor();
                EvictionTimer.schedule(evictor, delay, delay);
            }
        }
    }
  • softMinEvictableIdleTimeMillis
    es el tiempo mínimo que la conexión está inactiva. Después de alcanzar este valor, el enlace inactivo se eliminará y las conexiones inactivas mínimas se mantendrán; el
    valor predeterminado es DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = -1

  • numTestsPerEvictionRun
    detecta el número de objetos inactivos detectados cada vez que se ejecuta el subproceso del objeto inactivo;
    si numTestsPerEvictionRun> = 0, el valor más pequeño de numTestsPerEvictionRun y ​​el número de conexiones en el grupo se utiliza como el número de conexiones detectadas cada vez;
    si numTestsPerEvictionRun < 0, cada vez El número de conexiones comprobadas es el resultado de dividir el número total de conexiones en el grupo por el valor absoluto de este valor y redondear; el
    valor predeterminado DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3
    org.apache.commons.pool2.impl.GenericObjectPool

        private int getNumTests() {
            final int numTestsPerEvictionRun = getNumTestsPerEvictionRun();
            if (numTestsPerEvictionRun >= 0) {
                return Math.min(numTestsPerEvictionRun, idleObjects.size());
            }
            return (int) (Math.ceil(idleObjects.size() /
                    Math.abs((double) numTestsPerEvictionRun)));
        }
  • evictionPolicyClassName
    El nombre de clase de la política de desalojo ; el
    valor predeterminado DEFAULT_EVICTION_POLICY_CLASS_NAME = "org.apache.commons.pool2.impl.DefaultEvictionPolicy"
    org.apache.commons.pool2.impl.GenericObjectPool

       public final void setEvictionPolicyClassName(final String evictionPolicyClassName) {
            try {
                Class<?> clazz;
                try {
                    clazz = Class.forName(evictionPolicyClassName, true, Thread.currentThread().getContextClassLoader());
                } catch (final ClassNotFoundException e) {
                    clazz = Class.forName(evictionPolicyClassName);
                }
                final Object policy = clazz.newInstance();
                if (policy instanceof EvictionPolicy<?>) {
                    @SuppressWarnings("unchecked") // safe, because we just checked the class
                    final EvictionPolicy<T> evicPolicy = (EvictionPolicy<T>) policy;
                    this.evictionPolicy = evicPolicy;
                } else {
                    throw new IllegalArgumentException("[" + evictionPolicyClassName + "] does not implement EvictionPolicy");
                }
            } catch (final ClassNotFoundException e) {
                throw new IllegalArgumentException("Unable to create EvictionPolicy instance of type " + evictionPolicyClassName, e);
            } catch (final InstantiationException e) {
                throw new IllegalArgumentException("Unable to create EvictionPolicy instance of type " + evictionPolicyClassName, e);
            } catch (final IllegalAccessException e) {
                throw new IllegalArgumentException("Unable to create EvictionPolicy instance of type " + evictionPolicyClassName, e);
            }
        }
  • testOnCreate
    detecta si el objeto es válido cuando se crea (verdadero: sí). Configurar verdadero reducirá el rendimiento; el
    valor predeterminado DEFAULT_TEST_ON_CREATE = falso.
    org.apache.commons.pool2.impl.GenericObjectPool ##deredObject (préstamo largo finalMaxWaitMillis)

        PooledObject<T> p = null;
        // ...省略
        // 配置true,新创建对象都会检测对象是否有效 【 create && getTestOnCreate() 】
        if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
            boolean validate = false;
            Throwable validationThrowable = null;
            try {
                validate = factory.validateObject(p);
            } catch (final Throwable t) {
                PoolUtils.checkRethrow(t);
                validationThrowable = t;
            }
            if (!validate) {
                try {
                    destroy(p);
                    destroyedByBorrowValidationCount.incrementAndGet();
                } catch (final Exception e) {
                    // Ignore - validation failure is more important
                }
                p = null;
                if (create) {
                    final NoSuchElementException nsee = new NoSuchElementException("Unable to validate object");
                    nsee.initCause(validationThrowable);
                    throw nsee;
                }
            }
        }
  • testOnBorrow
    detecta si el objeto es válido al obtener el objeto del grupo de objetos (verdadero: sí), la configuración de verdadero reducirá el rendimiento; el
    valor predeterminado DEFAULT_TEST_ON_BORROW = false
    org.apache.commons.pool2.impl.GenericObjectPool ##deredObject (final long pedir prestadoMaxWaitMillis) **
    // 配置true,从对象池获取对象,总是要检测对象是否有效 【 getTestOnBorrow() 】
    if (p != null && (getTestOnBorrow() || create && getTestOnCreate())) {
        // ...省略
    }
  • testOnReturn
    detecta si el objeto es válido al devolver el objeto al grupo de objetos (verdadero: sí), la configuración de verdadero reducirá el rendimiento; el
    valor predeterminado DEFAULT_TEST_ON_RETURN = false
    org.apache.commons.pool2.impl.GenericObjectPool ## returnObject (obj T final)

        if (getTestOnReturn()) {
            if (!factory.validateObject(p)) {
                try {
                    destroy(p);
                } catch (final Exception e) {
                    swallowException(e);
                }
                try {
                    ensureIdle(1, false);
                } catch (final Exception e) {
                    swallowException(e);
                }
                updateStatsReturn(activeTime);
                return;
            }
        }
  • Si testWhileIdle
    detecta la validez del objeto cuando el hilo de detección de objetos inactivos detecta que el objeto no necesita ser eliminado. Se recomienda configurar en verdadero, lo que no afectará el rendimiento y garantizará la seguridad; el
    valor predeterminado DEFAULT_TEST_WHILE_IDLE = false
    org.apache.commons.pool2.impl.GenericObjectPool ## evict ()

        final boolean testWhileIdle = getTestWhileIdle();
        // .... 代码省略
        // 配置为true, 检测空闲对象线程检测到对象不需要移除时,检测对象的有效性
        if (testWhileIdle) {
            boolean active = false;
            try {
                factory.activateObject(underTest);
                active = true;
            } catch (final Exception e) {
                destroy(underTest);
                destroyedByEvictorCount.incrementAndGet();
            }
            if (active) {
                if (!factory.validateObject(underTest)) {
                    destroy(underTest);
                    destroyedByEvictorCount.incrementAndGet();
                } else {
                    try {
                        factory.passivateObject(underTest);
                    } catch (final Exception e) {
                        destroy(underTest);
                        destroyedByEvictorCount.incrementAndGet();
                    }
                }
            }
        }
  • timeBetweenEvictionRunsMillis
    ciclo de detección de conexión inactiva (en milisegundos); si es un valor negativo, significa que el hilo de detección no se ejecuta; el
    valor predeterminado es DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L
    org.apache.commons.pool2.impl.GenericObjectPool

        public GenericObjectPool(final PooledObjectFactory<T> factory, final GenericObjectPoolConfig config) {
            super(config, ONAME_BASE, config.getJmxNamePrefix());
            if (factory == null) {
                jmxUnregister(); // tidy up
                throw new IllegalArgumentException("factory may not be null");
            }
            this.factory = factory;
    
            idleObjects = new LinkedBlockingDeque<PooledObject<T>>(config.getFairness());
    
            setConfig(config);
            // 启动空闲连接检测线程
            startEvictor(getTimeBetweenEvictionRunsMillis());
        }
  • blockWhenExhausted
    Cuando no hay ningún objeto libre en el grupo de objetos, si la nueva solicitud para obtener el objeto está bloqueada (bloqueo verdadero, maxWaitMillis tendrá efecto; falso si el grupo de conexiones no tiene recursos y lanzará una excepción inmediatamente)
    Valor predeterminado DEFAULT_BLOCK_WHEN_EXHAUSTED = true
    org.apache.commons.pool2.impl.GenericObjectPool ##deredObject (préstamo largo finalMaxWaitMillis)

        final boolean blockWhenExhausted = getBlockWhenExhausted();
        // ... 省略
        if (blockWhenExhausted) {
            if (p == null) {
                if (borrowMaxWaitMillis < 0) {
                    p = idleObjects.takeFirst();
                } else {
                    p = idleObjects.pollFirst(borrowMaxWaitMillis,
                            TimeUnit.MILLISECONDS);
                }
            }
            if (p == null) {
                throw new NoSuchElementException(
                        "Timeout waiting for idle object");
            }
        } 
  • Si jmxEnabled
    está registrado con JMX
    predeterminado DEFAULT_JMX_ENABLE = true
    org.apache.commons.pool2.impl.BaseGenericObjectPool

        public BaseGenericObjectPool(final BaseObjectPoolConfig config, final String jmxNameBase, final String jmxNamePrefix) {
            if (config.getJmxEnabled()) {
                this.oname = jmxRegister(config, jmxNameBase, jmxNamePrefix);
            } else {
                this.oname = null;
            }
    
            // Populate the creation stack trace
            this.creationStackTrace = getStackTrace(new Exception());
    
            // save the current TCCL (if any) to be used later by the evictor Thread
            final ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                factoryClassLoader = null;
            } else {
                factoryClassLoader = new WeakReference<ClassLoader>(cl);
            }
    
            fairness = config.getFairness();
        }
  • jmxNamePrefix
    Prefijo JMX
    valor predeterminado DEFAULT_JMX_NAME_PREFIX = "pool"
    org.apache.commons.pool2.impl.GenericObjectPool

        // JMX specific attributes
        private static final String ONAME_BASE = "org.apache.commons.pool2:type=GenericObjectPool,name=";
    
        public GenericObjectPool(final PooledObjectFactory<T> factory, final GenericObjectPoolConfig config) {
            // 参见上述 jmxEnabled 部分
            super(config, ONAME_BASE, config.getJmxNamePrefix());
            // .....
        }
  • jmxNameBase
    utiliza base + jmxNamePrefix + i para generar el ObjectName
    valor predeterminado DEFAULT_JMX_NAME_BASE = null, y la GenericObjectPool método de construcción utiliza ONAME_BASE inicialización.

        private ObjectName jmxRegister(final BaseObjectPoolConfig config,final String jmxNameBase, String jmxNamePrefix) {
            ObjectName objectName = null;
            final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            int i = 1;
            boolean registered = false;
            String base = config.getJmxNameBase();
            if (base == null) {
                base = jmxNameBase;
            }
            while (!registered) {
                try {
                    ObjectName objName;
                    if (i == 1) {
                        objName = new ObjectName(base + jmxNamePrefix);
                    } else {
                        objName = new ObjectName(base + jmxNamePrefix + i);
                    }
                    mbs.registerMBean(this, objName);
                    objectName = objName;
                    registered = true;
                } catch (final MalformedObjectNameException e) {
                    if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals(jmxNamePrefix) && jmxNameBase.equals(base)) {
                        // 如果走到这步,就跳过jmx注册,应该不会发生
                        registered = true;
                    } else {
                        // 前者使用的名称不是默认配置,则使用默认配置替代
                        jmxNamePrefix =
                                BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX;
                        base = jmxNameBase;
                    }
                } catch (final InstanceAlreadyExistsException e) {
                    // 增加一个索引,再试一次
                    i++;
                } catch (final MBeanRegistrationException e) {
                    // 如果走到这步,就跳过jmx注册,应该不会发生
                    registered = true;
                } catch (final NotCompliantMBeanException e) {
                    // 如果走到这步,就跳过jmx注册,应该不会发生
                    registered = true;
                }
            }
            return objectName;
        }
    

2. Parámetros de configuración de la subclase GenericObjectPoolConfig

/**
 * A simple "struct" encapsulating the configuration for a
 * {@link GenericObjectPool}.
 *  * <p>
 * This class is not thread-safe; it is only intended to be used to provide
 * attributes used when creating a pool.
 *  * @since 2.0
 */
public class GenericObjectPoolConfig extends BaseObjectPoolConfig {

    private int maxTotal = DEFAULT_MAX_TOTAL;

    private int maxIdle = DEFAULT_MAX_IDLE;

    private int minIdle = DEFAULT_MIN_IDLE;
}
  • maxTotal
    número máximo de conexiones, el valor predeterminado DEFAULT_MAX_TOTAL = 8
  • maxIdle
    número máximo de conexiones inactivas, el valor predeterminado DEFAULT_MAX_IDLE = 8
  • minIdle
    número mínimo de conexiones inactivas, el valor predeterminado DEFAULT_MIN_IDLE = 0

Supongo que te gusta

Origin blog.51cto.com/huazie/2676978
Recomendado
Clasificación