Example usage for org.apache.commons.pool2.impl GenericKeyedObjectPoolConfig setJmxNamePrefix

List of usage examples for org.apache.commons.pool2.impl GenericKeyedObjectPoolConfig setJmxNamePrefix

Introduction

In this page you can find the example usage for org.apache.commons.pool2.impl GenericKeyedObjectPoolConfig setJmxNamePrefix.

Prototype

public void setJmxNamePrefix(String jmxNamePrefix) 

Source Link

Document

Sets the value of the JMX name prefix that will be used as part of the name assigned to JMX enabled pools created with this configuration instance.

Usage

From source file:JDBCPool.dbcp.demo.sourcecode.PoolableConnectionFactory.java

/**
 * ?PoolDefaultPooledObject??Connection//from w ww. ja v a 2  s  .c om
 */
@Override
public PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = _connFactory.createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }

    try {
        initializeConnection(conn); //?SQL?SQL
    } catch (SQLException sqle) {
        // Make sure the connection is closed
        try {
            conn.close();
        } catch (SQLException ignore) {
            // ignore
        }
        // Rethrow original exception so it is visible to caller
        throw sqle;
    }

    long connIndex = connectionIndex.getAndIncrement();

    if (poolStatements) {
        conn = new PoolingConnection(conn);
        GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(maxOpenPreparedStatements);
        if (dataSourceJmxName != null) {
            StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
                (PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(_cacheState);
    }

    // Register this connection with JMX
    ObjectName connJmxName;
    if (dataSourceJmxName == null) {
        connJmxName = null;
    } else {
        connJmxName = new ObjectName(
                dataSourceJmxName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex);
    }

    PoolableConnection pc = new PoolableConnection(conn, _pool, connJmxName, _disconnectionSqlCodes,
            _fastFailValidation);

    return new DefaultPooledObject<>(pc);
}

From source file:org.jmxtrans.embedded.output.GraphitePickleWriter.java

/**
 * Load settings, initialize the {@link SocketWriter} pool and test the connection to the graphite server.
 *
 * a {@link Logger#warn(String)} message is emitted if the connection to the graphite server fails.
 *///from  ww w  . j a  va 2  s  . c  o  m
@Override
public void start() {
    int port = getIntSetting(SETTING_PORT, DEFAULT_GRAPHITE_SERVER_PORT);
    String host = getStringSetting(SETTING_HOST);
    graphiteServerHostAndPort = new HostAndPort(host, port);

    logger.info("Start Graphite Pickle writer connected to '{}'...", graphiteServerHostAndPort);

    metricPathPrefix = getStringSetting(SETTING_NAME_PREFIX, DEFAULT_NAME_PREFIX);
    metricPathPrefix = getStrategy().resolveExpression(metricPathPrefix);
    if (!metricPathPrefix.isEmpty() && !metricPathPrefix.endsWith(".")) {
        metricPathPrefix = metricPathPrefix + ".";
    }

    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setTestOnBorrow(getBooleanSetting("pool.testOnBorrow", true));
    config.setTestWhileIdle(getBooleanSetting("pool.testWhileIdle", true));
    config.setMaxTotal(getIntSetting("pool.maxActive", -1));
    config.setMaxIdlePerKey(getIntSetting("pool.maxIdle", -1));
    config.setMinEvictableIdleTimeMillis(
            getLongSetting("pool.minEvictableIdleTimeMillis", TimeUnit.MINUTES.toMillis(5)));
    config.setTimeBetweenEvictionRunsMillis(
            getLongSetting("pool.timeBetweenEvictionRunsMillis", TimeUnit.MINUTES.toMillis(5)));
    config.setJmxNameBase(
            "org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=GraphitePickleWriter,name=");
    config.setJmxNamePrefix(graphiteServerHostAndPort.getHost() + "_" + graphiteServerHostAndPort.getPort());

    int socketConnectTimeoutInMillis = getIntSetting("graphite.socketConnectTimeoutInMillis",
            SocketOutputStreamPoolFactory.DEFAULT_SOCKET_CONNECT_TIMEOUT_IN_MILLIS);

    socketOutputStreamPool = new GenericKeyedObjectPool<HostAndPort, SocketOutputStream>(
            new SocketOutputStreamPoolFactory(socketConnectTimeoutInMillis), config);

    if (isEnabled()) {
        try {
            SocketOutputStream socketOutputStream = socketOutputStreamPool
                    .borrowObject(graphiteServerHostAndPort);
            socketOutputStreamPool.returnObject(graphiteServerHostAndPort, socketOutputStream);
        } catch (Exception e) {
            logger.warn("Test Connection: FAILURE to connect to Graphite server '{}'",
                    graphiteServerHostAndPort, e);
        }
    }
    try {
        Class.forName("org.python.modules.cPickle");
    } catch (ClassNotFoundException e) {
        throw new EmbeddedJmxTransException("jython librarie is required by the " + getClass().getSimpleName()
                + " but is not found in the classpath. Please add org.python:jython:2.5.3+ to the classpath.");
    }
}

From source file:org.jmxtrans.embedded.output.GraphiteWriter.java

/**
 * Load settings, initialize the {@link SocketWriter} pool and test the connection to the graphite server.
 *
 * a {@link Logger#warn(String)} message is emitted if the connection to the graphite server fails.
 *//*from  ww  w. j ava2 s  .  co m*/
@Override
public void start() {
    int port = getIntSetting(SETTING_PORT, DEFAULT_GRAPHITE_SERVER_PORT);
    String host = getStringSetting(SETTING_HOST);
    graphiteServerHostAndPort = new HostAndPort(host, port);

    logger.info("Start Graphite writer connected to '{}'...", graphiteServerHostAndPort);

    metricPathPrefix = getStringSetting(SETTING_NAME_PREFIX, DEFAULT_NAME_PREFIX);
    metricPathPrefix = getStrategy().resolveExpression(metricPathPrefix);
    if (!metricPathPrefix.isEmpty() && !metricPathPrefix.endsWith(".")) {
        metricPathPrefix = metricPathPrefix + ".";
    }

    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setTestOnBorrow(getBooleanSetting("pool.testOnBorrow", true));
    config.setTestWhileIdle(getBooleanSetting("pool.testWhileIdle", true));
    config.setMaxTotal(getIntSetting("pool.maxActive", -1));
    config.setMaxIdlePerKey(getIntSetting("pool.maxIdle", -1));
    config.setMinEvictableIdleTimeMillis(
            getLongSetting("pool.minEvictableIdleTimeMillis", TimeUnit.MINUTES.toMillis(5)));
    config.setTimeBetweenEvictionRunsMillis(
            getLongSetting("pool.timeBetweenEvictionRunsMillis", TimeUnit.MINUTES.toMillis(5)));
    config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=GraphiteWriter,name=");
    config.setJmxNamePrefix(graphiteServerHostAndPort.getHost() + "_" + graphiteServerHostAndPort.getPort());

    int socketConnectTimeoutInMillis = getIntSetting("graphite.socketConnectTimeoutInMillis",
            SocketWriterPoolFactory.DEFAULT_SOCKET_CONNECT_TIMEOUT_IN_MILLIS);

    String protocol = getStringSetting(SETTING_PROTOCOL, null);
    if (protocol != null && protocol.equalsIgnoreCase(PROTOCOL_UDP)) {
        socketWriterPool = new GenericKeyedObjectPool<HostAndPort, SocketWriter>(
                new UDPSocketWriterPoolFactory(StandardCharsets.UTF_8), config);
    } else {
        if (protocol == null) {
            // protocol not specified, use default one
            logger.info("Protocol unspecified, default protocol '{}' will be used.", PROTOCOL_TCP);
        } else if (PROTOCOL_TCP.equalsIgnoreCase(protocol) == false) {
            // unknown or protocol, use default one
            logger.warn("Unknown protocol specified '{}', default protocol '{}' will be used instead.",
                    protocol, PROTOCOL_TCP);
        }
        socketWriterPool = new GenericKeyedObjectPool<HostAndPort, SocketWriter>(
                new SocketWriterPoolFactory(StandardCharsets.UTF_8, socketConnectTimeoutInMillis), config);
    }

    if (isEnabled()) {
        try {
            SocketWriter socketWriter = socketWriterPool.borrowObject(graphiteServerHostAndPort);
            socketWriterPool.returnObject(graphiteServerHostAndPort, socketWriter);
        } catch (Exception e) {
            logger.warn("Test Connection: FAILURE to connect to Graphite server '{}'",
                    graphiteServerHostAndPort, e);
        }
    }
}

From source file:org.jmxtrans.embedded.util.pool.ManagedGenericKeyedObjectPoolTest.java

@Test
public void testMbeanAttributeAccess() throws Exception {
    BaseKeyedPooledObjectFactory<String, String> factory = new BaseKeyedPooledObjectFactory<String, String>() {
        @Override//from   ww  w.  j ava  2 s. c  om
        public String create(String key) throws Exception {
            return key;
        }

        @Override
        public PooledObject<String> wrap(String value) {
            return new DefaultPooledObject<String>(value);
        }
    };
    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setJmxNameBase("org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=MyWriter,name=");
    config.setJmxNamePrefix("my-host_1234");
    GenericKeyedObjectPool<String, String> objectPool = new GenericKeyedObjectPool<String, String>(factory,
            config);

    ObjectName objectName = new ObjectName(
            "org.jmxtrans.embedded:type=GenericKeyedObjectPool,writer=MyWriter,name=my-host_1234");
    MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        Object numIdle = mbeanServer.getAttribute(objectName, "NumIdle");
        assertThat(numIdle, instanceOf(Number.class));

    } finally {
        mbeanServer.unregisterMBean(objectName);
    }
}

From source file:org.springframework.ldap.pool2.factory.PooledContextSource.java

private GenericKeyedObjectPoolConfig getConfig(PoolConfig poolConfig) {
    GenericKeyedObjectPoolConfig objectPoolConfig = new GenericKeyedObjectPoolConfig();

    objectPoolConfig.setMaxTotalPerKey(poolConfig.getMaxTotalPerKey());
    objectPoolConfig.setMaxTotal(poolConfig.getMaxTotal());

    objectPoolConfig.setMaxIdlePerKey(poolConfig.getMaxIdlePerKey());
    objectPoolConfig.setMinIdlePerKey(poolConfig.getMinIdlePerKey());

    objectPoolConfig.setTestWhileIdle(poolConfig.isTestWhileIdle());
    objectPoolConfig.setTestOnReturn(poolConfig.isTestOnReturn());
    objectPoolConfig.setTestOnCreate(poolConfig.isTestOnCreate());
    objectPoolConfig.setTestOnBorrow(poolConfig.isTestOnBorrow());

    objectPoolConfig.setTimeBetweenEvictionRunsMillis(poolConfig.getTimeBetweenEvictionRunsMillis());
    objectPoolConfig.setEvictionPolicyClassName(poolConfig.getEvictionPolicyClassName());
    objectPoolConfig.setMinEvictableIdleTimeMillis(poolConfig.getMinEvictableIdleTimeMillis());
    objectPoolConfig.setNumTestsPerEvictionRun(poolConfig.getNumTestsPerEvictionRun());
    objectPoolConfig.setSoftMinEvictableIdleTimeMillis(poolConfig.getSoftMinEvictableIdleTimeMillis());

    objectPoolConfig.setJmxEnabled(poolConfig.isJmxEnabled());
    objectPoolConfig.setJmxNameBase(poolConfig.getJmxNameBase());
    objectPoolConfig.setJmxNamePrefix(poolConfig.getJmxNamePrefix());

    objectPoolConfig.setMaxWaitMillis(poolConfig.getMaxWaitMillis());

    objectPoolConfig.setFairness(poolConfig.isFairness());
    objectPoolConfig.setBlockWhenExhausted(poolConfig.isBlockWhenExhausted());
    objectPoolConfig.setLifo(poolConfig.isLifo());

    return objectPoolConfig;
}