Create a new {@link ShardedJedisPool}.

@param poolConfig
format {@code host1:port1,host2:port2,...}, default Redis port is used if not
specified
@param password
@param timeoutMs
@return
761220
public static ShardedJedisPool newShardedJedisPool(JedisPoolConfig poolConfig,
            String hostsAndPorts, String password, int timeoutMs) {
        List<JedisShardInfo> shards = new ArrayList<>();
        String[] hapList = hostsAndPorts.split("[,;\\s]+");
        for (String hostAndPort : hapList) {
            String[] tokens = hostAndPort.split(":");
            String host = tokens.length > 0 ? tokens[0] : Protocol.DEFAULT_HOST;
            int port = tokens.length > 1 ? Integer.parseInt(tokens[1]) : Protocol.DEFAULT_PORT;
            JedisShardInfo shardInfo = new JedisShardInfo(host, port, timeoutMs);
            shardInfo.setPassword(StringUtils.isBlank(password) ? null : password);
            shards.add(shardInfo);
        }
        ShardedJedisPool jedisPool = new ShardedJedisPool(
                poolConfig != null ? poolConfig : defaultJedisPoolConfig(), shards);
        return jedisPool;
    }
43203
public static Pool retrievePool(UrlParser urlParser) {
    if (!poolMap.containsKey(urlParser)) {
      synchronized (poolMap) {
        if (!poolMap.containsKey(urlParser)) {
          if (poolExecutor == null) {
            poolExecutor = new ScheduledThreadPoolExecutor(1,
                new MariaDbThreadFactory("MariaDbPool-maxTimeoutIdle-checker"));
          }
          Pool pool = new Pool(urlParser, poolIndex.incrementAndGet(), poolExecutor);
          poolMap.put(urlParser, pool);
          return pool;
        }
      }
    }
    return poolMap.get(urlParser);
  }
1002281
public static PoolConfig newLdaptivePoolConfig(final AbstractLdapProperties l) {
        LOGGER.debug("Creating LDAP connection pool configuration for [{}]", l.getLdapUrl());
        val pc = new PoolConfig();
        pc.setMinPoolSize(l.getMinPoolSize());
        pc.setMaxPoolSize(l.getMaxPoolSize());
        pc.setValidateOnCheckOut(l.isValidateOnCheckout());
        pc.setValidatePeriodically(l.isValidatePeriodically());
        pc.setValidatePeriod(Beans.newDuration(l.getValidatePeriod()));
        pc.setValidateTimeout(Beans.newDuration(l.getValidateTimeout()));
        return pc;
    }
695657
public ServerSocketBar create(InetAddress host, int port)
    throws IOException, GeneralSecurityException
  {
    SSLServerSocketFactory ssFactory = null;
    
    if (_keyStore != null) {
      SSLContext sslContext = SSLContext.getInstance(_sslContext);

      KeyManagerFactory kmf
        = KeyManagerFactory.getInstance(keyManagerFactory());
    
      kmf.init(_keyStore, keyStorePassword().toCharArray());
      
      sslContext.init(kmf.getKeyManagers(), null, null);

      /*
      if (_cipherSuites != null)
        sslContext.createSSLEngine().setEnabledCipherSuites(_cipherSuites);

      if (_protocols != null)
        sslContext.createSSLEngine().setEnabledProtocols(_protocols);
      */
      
      SSLEngine engine = sslContext.createSSLEngine();
      
      engine.setEnabledProtocols(enabledProtocols(engine.getSupportedProtocols()));

      ssFactory = sslContext.getServerSocketFactory();
    }
    else {
      ssFactory = createAnonymousServerFactory(host, port);
    }
    
    ServerSocket serverSocket;

    int listen = 100;

    if (host == null)
      serverSocket = ssFactory.createServerSocket(port, listen);
    else
      serverSocket = ssFactory.createServerSocket(port, listen, host);

    SSLServerSocket sslServerSocket = (SSLServerSocket) serverSocket;
    
    if (_cipherSuites != null) {
      sslServerSocket.setEnabledCipherSuites(_cipherSuites);
    }
    
    if (_cipherSuitesForbidden != null) {
      String []cipherSuites = sslServerSocket.getEnabledCipherSuites();
      
      if (cipherSuites == null)
        cipherSuites = sslServerSocket.getSupportedCipherSuites();
      
      ArrayList<String> cipherList = new ArrayList<String>();
      
      for (String cipher : cipherSuites) {
        if (! isCipherForbidden(cipher, _cipherSuitesForbidden)) {
          cipherList.add(cipher);
        }
      }
      
      cipherSuites = new String[cipherList.size()];
      cipherList.toArray(cipherSuites);
      
      sslServerSocket.setEnabledCipherSuites(cipherSuites);
    }

    sslServerSocket.setEnabledProtocols(enabledProtocols(sslServerSocket.getSupportedProtocols()));
    
    if ("required".equals(_verifyClient))
      sslServerSocket.setNeedClientAuth(true);
    else if ("optional".equals(_verifyClient))
      sslServerSocket.setWantClientAuth(true);

    return new ServerSocketWrapper(serverSocket);
  }
136429
def create_jdbc_connection_pool(name, server=None, **kwargs):
    '''
    
    '''
    defaults = {
        'allowNonComponentCallers': False,
        'associateWithThread': False,
        'connectionCreationRetryAttempts': '0',
        'connectionCreationRetryIntervalInSeconds': '10',
        'connectionLeakReclaim': False,
        'connectionLeakTimeoutInSeconds': '0',
        'connectionValidationMethod': 'table',
        'datasourceClassname': '',
        'description': '',
        'driverClassname': '',
        'failAllConnections': False,
        'idleTimeoutInSeconds': '300',
        'initSql': '',
        'isConnectionValidationRequired': False,
        'isIsolationLevelGuaranteed': True,
        'lazyConnectionAssociation': False,
        'lazyConnectionEnlistment': False,
        'matchConnections': False,
        'maxConnectionUsageCount': '0',
        'maxPoolSize': '32',
        'maxWaitTimeInMillis': 60000,
        'name': name,
        'nonTransactionalConnections': False,
        'ping': False,
        'poolResizeQuantity': '2',
        'pooling': True,
        'resType': '',
        'sqlTraceListeners': '',
        'statementCacheSize': '0',
        'statementLeakReclaim': False,
        'statementLeakTimeoutInSeconds': '0',
        'statementTimeoutInSeconds': '-1',
        'steadyPoolSize': '8',
        'target': 'server',
        'transactionIsolationLevel': '',
        'validateAtmostOncePeriodInSeconds': '0',
        'validationClassname': '',
        'validationTableName': '',
        'wrapJdbcObjects': True
    }

    # Data = defaults + merge kwargs + poolname
    data = defaults
    data.update(kwargs)

    # Check resType against acceptable values
    if data['resType'] not in (
            'javax.sql.DataSource',
            'javax.sql.XADataSource',
            'javax.sql.ConnectionPoolDataSource',
            'java.sql.Driver'
       ):
        raise CommandExecutionError('Invalid resource type')

    # Check connectionValidationMethod against acceptable velues
    if data['connectionValidationMethod'] not in (
            'auto-commit',
            'meta-data',
            'table',
            'custom-validation'
       ):
        raise CommandExecutionError('Invalid connection validation method')

    if data['transactionIsolationLevel'] \
       and data['transactionIsolationLevel'] not in (
               'read-uncommitted',
               'read-committed',
               'repeatable-read',
               'serializable'
       ):
        raise CommandExecutionError('Invalid transaction isolation level')

    if not data['datasourceClassname'] \
       and data['resType'] in (
               'javax.sql.DataSource',
               'javax.sql.ConnectionPoolDataSource',
               'javax.sql.XADataSource'
       ):
        raise CommandExecutionError('No datasource class name while using datasource resType')
    if not data['driverClassname'] and data['resType'] == 'java.sql.Driver':
        raise CommandExecutionError('No driver class nime while using driver resType')

    return _create_element(name, 'resources/jdbc-connection-pool', data, server)
1152747
private PoolEntry createPoolEntry()
   {
      try {
         final PoolEntry poolEntry = newPoolEntry();

         final long maxLifetime = config.getMaxLifetime();
         if (maxLifetime > 0) {
            // variance up to 2.5% of the maxlifetime
            final long variance = maxLifetime > 10_000 ? ThreadLocalRandom.current().nextLong( maxLifetime / 40 ) : 0;
            final long lifetime = maxLifetime - variance;
            poolEntry.setFutureEol(houseKeepingExecutorService.schedule(
               () -> {
                  if (softEvictConnection(poolEntry, "(connection has passed maxLifetime)", false /* not owner */)) {
                     addBagItem(connectionBag.getWaitingThreadCount());
                  }
               },
               lifetime, MILLISECONDS));
         }

         return poolEntry;
      }
      catch (ConnectionSetupException e) {
         if (poolState == POOL_NORMAL) { // we check POOL_NORMAL to avoid a flood of messages if shutdown() is running concurrently
            logger.error("{} - Error thrown while acquiring connection from data source", poolName, e.getCause());
            lastConnectionFailure.set(e);
         }
         return null;
      }
      catch (SQLException e) {
         if (poolState == POOL_NORMAL) { // we check POOL_NORMAL to avoid a flood of messages if shutdown() is running concurrently
            logger.debug("{} - Cannot acquire connection from data source", poolName, e);
            lastConnectionFailure.set(new ConnectionSetupException(e));
         }
         return null;
      }
      catch (Exception e) {
         if (poolState == POOL_NORMAL) { // we check POOL_NORMAL to avoid a flood of messages if shutdown() is running concurrently
            logger.error("{} - Error thrown while acquiring connection from data source", poolName, e);
            lastConnectionFailure.set(new ConnectionSetupException(e));
         }
         return null;
      }
   }
1158569
def _connect(host=None, port=None, db=None, password=None):
    '''
    
    '''
    if not host:
        host = __salt__['config.option']('redis.host')
    if not port:
        port = __salt__['config.option']('redis.port')
    if not db:
        db = __salt__['config.option']('redis.db')
    if not password:
        password = __salt__['config.option']('redis.password')

    return redis.StrictRedis(host, port, db, password, decode_responses=True)
1144172
@Override
    public void createAsync(SocketDestination dest,
                            KeyedResourcePool<SocketDestination, SocketAndStreams> pool)
            throws Exception {
        Socket socket = new Socket();
        socket.setReceiveBufferSize(this.socketBufferSize);
        socket.setSendBufferSize(this.socketBufferSize);
        socket.setTcpNoDelay(true);
        socket.setSoTimeout(soTimeoutMs);
        socket.setKeepAlive(this.socketKeepAlive);
        socket.connect(new InetSocketAddress(dest.getHost(), dest.getPort()), soTimeoutMs);

        recordSocketCreation(dest, socket);

        SocketAndStreams sands = new SocketAndStreams(socket, dest.getRequestFormatType());
        negotiateProtocol(sands, dest.getRequestFormatType());

        pool.checkin(dest, sands);
    }
337446
function PoolCluster(args) {
  const opts = new PoolClusterOptions(args);
  const nodes = {};
  let cachedPatterns = {};
  let nodeCounter = 0;

  /**
   * Add a new pool node to cluster.
   *
   * @param id      identifier
   * @param config  pool configuration
   */
  this.add = (id, config) => {
    let identifier;
    if (typeof id === 'string' || id instanceof String) {
      identifier = id;
      if (nodes[identifier])
        throw new Error("Node identifier '" + identifier + "' already exist !");
    } else {
      identifier = 'PoolNode-' + nodeCounter++;
    }
    const options = new PoolOptions(config);
    const pool = _createPool(options);
    pool.initialize();
    nodes[identifier] = pool;
  };

  /**
   * End cluster (and underlying pools).
   *
   * @return {Promise<any[]>}
   */
  this.end = () => {
    cachedPatterns = {};
    const poolEndPromise = [];
    Object.keys(nodes).forEach(pool => {
      poolEndPromise.push(nodes[pool].end());
      delete nodes[pool];
    });

    return Promise.all(poolEndPromise);
  };

  this.of = (pattern, selector) => {
    return new FilteredPoolCluster(this, pattern, selector);
  };

  /**
   * Remove nodes according to pattern.
   *
   * @param pattern  pattern
   */
  this.remove = pattern => {
    if (!pattern)
      throw new Error(
        'pattern parameter in Cluster.remove(pattern)  is mandatory'
      );

    const regex = RegExp(pattern);
    Object.keys(nodes).forEach(key => {
      if (regex.test(key)) {
        nodes[key].end();
        delete nodes[key];
        cachedPatterns = {};
      }
    });
  };

  /**
   * Get connection from available pools matching pattern, according to selector
   *
   * @param pattern       pattern filter (not mandatory)
   * @param selector      node selector ('RR','RANDOM' or 'ORDER')
   * @return {Promise}
   */
  this.getConnection = (pattern, selector) => {
    return _getConnection(pattern, selector);
  };

  /**
   * Force using callback methods.
   */
  this.setCallback = () => {
    this.getConnection = _getConnectionCallback;
    _createPool = _createPoolCallback;
  };

  /**
   * Get connection from available pools matching pattern, according to selector
   * with additional parameter to avoid reusing failing node
   *
   * @param pattern       pattern filter (not mandatory)
   * @param selector      node selector ('RR','RANDOM' or 'ORDER')
   * @param avoidNodeKey  failing node
   * @param lastError     last error
   * @return {Promise}
   * @private
   */
  const _getConnection = (pattern, selector, avoidNodeKey, lastError) => {
    const matchingNodeList = _matchingNodes(pattern || /^/);

    if (matchingNodeList.length === 0) {
      if (Object.keys(nodes).length === 0)
        return Promise.reject(
          new Error(
            'No node have been added to cluster or nodes have been removed due to too much connection error'
          )
        );
      if (avoidNodeKey === undefined)
        return Promise.reject(
          new Error("No node found for pattern '" + pattern + "'")
        );
      const errMsg =
        "No Connection available for '" +
        pattern +
        "'" +
        (lastError ? '. Last connection error was: ' + lastError.message : '');
      return Promise.reject(new Error(errMsg));
    }

    const retry = _getConnection.bind(this, pattern, selector);
    try {
      const nodeKey = _selectPool(matchingNodeList, selector, avoidNodeKey);
      return _handleConnectionError(matchingNodeList, nodeKey, retry);
    } catch (e) {
      return Promise.reject(e);
    }
  };

  let _createPool = options => {
    return new Pool(options, false);
  };

  const _createPoolCallback = options => {
    return new PoolCallback(options, false);
  };

  /**
   * Get connection from available pools matching pattern, according to selector
   * with additional parameter to avoid reusing failing node
   *
   * @param pattern       pattern filter (not mandatory)
   * @param selector      node selector ('RR','RANDOM' or 'ORDER')
   * @param callback      callback function
   * @param avoidNodeKey  failing node
   * @private
   */
  const _getConnectionCallback = (
    pattern,
    selector,
    callback,
    avoidNodeKey
  ) => {
    const matchingNodeList = _matchingNodes(pattern || /^/);

    if (matchingNodeList.length === 0) {
      if (Object.keys(nodes).length === 0) {
        callback(
          new Error(
            'No node have been added to cluster or nodes have been removed due to too much connection error'
          )
        );
        return;
      }
      callback(new Error("No node found for pattern '" + pattern + "'"));
      return;
    }

    const retry = _getConnectionCallback.bind(
      this,
      pattern,
      selector,
      callback
    );
    try {
      const nodeKey = _selectPool(matchingNodeList, selector, avoidNodeKey);
      _handleConnectionCallbackError(
        matchingNodeList,
        nodeKey,
        retry,
        callback
      );
    } catch (e) {
      callback(e);
    }
  };

  /**
   * Selecting nodes according to pattern.
   *
   * @param pattern pattern
   * @return {*}
   * @private
   */
  const _matchingNodes = pattern => {
    if (cachedPatterns[pattern]) return cachedPatterns[pattern];

    const regex = RegExp(pattern);
    const matchingNodeList = [];
    Object.keys(nodes).forEach(key => {
      if (regex.test(key)) {
        matchingNodeList.push(key);
      }
    });

    cachedPatterns[pattern] = matchingNodeList;
    return matchingNodeList;
  };

  /**
   * Select next node to be chosen in nodeList according to selector and failed nodes.
   *
   * @param nodeList        current node list
   * @param selectorParam   selector
   * @param avoidNodeKey    last failing node to avoid selecting this one.
   * @return {Promise}
   * @private
   */
  const _selectPool = (nodeList, selectorParam, avoidNodeKey) => {
    const selector = selectorParam || opts.defaultSelector;
    let retry = 0;
    let selectorFct;
    let nodeKey;
    switch (selector) {
      case 'RR':
        selectorFct = roundRobinSelector;
        break;

      case 'RANDOM':
        selectorFct = randomSelector;
        break;

      case 'ORDER':
        selectorFct = orderedSelector;
        break;

      default:
        throw new Error(
          "Wrong selector value '" +
            selector +
            "'. Possible values are 'RR','RANDOM' or 'ORDER'"
        );
    }

    nodeKey = selectorFct(nodeList, retry);
    while (
      (avoidNodeKey === nodeKey || nodes[nodeKey].timeout > Date.now()) &&
      retry < nodeList.length - 1
    ) {
      retry++;
      nodeKey = selectorFct(nodeList);
    }
    return nodeKey;
  };

  /**
   * Round robin selector: using nodes one after the other.
   *
   * @param nodeList  node list
   * @return {String}
   */
  const roundRobinSelector = nodeList => {
    let lastRoundRobin = nodeList.lastRrIdx;
    if (lastRoundRobin === undefined) lastRoundRobin = -1;
    if (++lastRoundRobin >= nodeList.length) lastRoundRobin = 0;
    nodeList.lastRrIdx = lastRoundRobin;
    return nodeList[lastRoundRobin];
  };

  /**
   * Random selector: use a random node.
   *
   * @param nodeList  node list
   * @return {String}
   */
  const randomSelector = nodeList => {
    let randomIdx = Math.floor(Math.random() * nodeList.length);
    return nodeList[randomIdx];
  };

  /**
   * Ordered selector: always use the nodes in sequence, unless failing.
   *
   * @param nodeList  node list
   * @param retry     sequence number if last node is tagged has failing
   * @return {String}
   */
  const orderedSelector = (nodeList, retry) => {
    return nodeList[retry];
  };

  /**
   * Connect, or if fail handle retry / set timeout error
   *
   * @param nodeList    current node list
   * @param nodeKey     node name to connect
   * @param retryFct    retry function
   * @return {Promise}
   * @private
   */
  const _handleConnectionError = (nodeList, nodeKey, retryFct) => {
    const node = nodes[nodeKey];
    return node
      .getConnection()
      .then(conn => {
        node.errorCount = 0;
        return Promise.resolve(conn);
      })
      .catch(err => {
        node.errorCount = node.errorCount ? node.errorCount + 1 : 1;
        if (node.errorCount >= opts.removeNodeErrorCount && nodes[nodeKey]) {
          if (opts.restoreNodeTimeout === 0) {
            delete nodes[nodeKey];
            cachedPatterns = {};
            delete nodeList.lastRrIdx;
            //remove node from configuration if not already removed
            node.end().catch(err => {
              // dismiss error
            });
          } else {
            node.timeout = Date.now() + opts.restoreNodeTimeout;
          }
          if (nodeList.length === 0) return Promise.reject(err);
        }

        if (opts.canRetry) return retryFct(nodeKey, err);
        return Promise.reject(err);
      });
  };

  /**
   * Connect, or if fail handle retry / set timeout error
   *
   * @param nodeList    current node list
   * @param nodeKey     node name to connect
   * @param retryFct    retry function
   * @param callback    callback function
   * @private
   */
  const _handleConnectionCallbackError = (
    nodeList,
    nodeKey,
    retryFct,
    callback
  ) => {
    const node = nodes[nodeKey];
    node.getConnection((err, conn) => {
      if (err) {
        node.errorCount = node.errorCount ? node.errorCount + 1 : 1;
        if (node.errorCount >= opts.removeNodeErrorCount && nodes[nodeKey]) {
          if (opts.restoreNodeTimeout === 0) {
            delete nodes[nodeKey];
            cachedPatterns = {};
            delete nodeList.lastRrIdx;
            //remove node from configuration if not already removed
            node.end(() => {
              //dismiss error
            });
          } else {
            node.timeout = Date.now() + opts.restoreNodeTimeout;
          }
          if (nodeList.length === 0) return Promise.reject(err);
        }

        if (opts.canRetry) return retryFct(nodeKey);
        callback(err);
      } else {
        node.errorCount = 0;
        callback(null, conn);
      }
    });
  };

  //*****************************************************************
  // internal public testing methods
  //*****************************************************************

  function TestMethods() {}
  TestMethods.prototype.getNodes = () => {
    return nodes;
  };

  this.__tests = new TestMethods();
}
49378
public static JedisCluster newJedisCluster(JedisPoolConfig poolConfig, String hostsAndPorts,
            int timeoutMs) {
        return newJedisCluster(poolConfig, hostsAndPorts, null, timeoutMs, 3);
    }
1121073
def create_pool(*)
      @connection = ConnectionPool.new(@config.size) do
        client = EM.connect_unix_domain(@config.sock, Connection)
        client.on_connect = self.method(:on_connect)
        client.on_disconnect = self.method(:on_disconnect)
        client
      end
    end
661882
function PoolCluster(config) {
  EventEmitter.call(this);

  config = config || {};
  this._canRetry = typeof config.canRetry === 'undefined' ? true : config.canRetry;
  this._defaultSelector = config.defaultSelector || 'RR';
  this._removeNodeErrorCount = config.removeNodeErrorCount || 5;
  this._restoreNodeTimeout = config.restoreNodeTimeout || 0;

  this._closed = false;
  this._findCaches = Object.create(null);
  this._lastId = 0;
  this._namespaces = Object.create(null);
  this._nodes = Object.create(null);
}
895495
public static RedisCommandTimeoutException createTimeoutException(String message, Duration timeout) {
        return new RedisCommandTimeoutException(
                String.format("%s. Command timed out after %s", message, formatTimeout(timeout)));
    }
507059
public static synchronized void createManagedConnectionPool(String poolName, Object mcp)
   {
      log.tracef("%s", new TraceEvent(poolName,
                                      Integer.toHexString(System.identityHashCode(mcp)),
                                      TraceEvent.MANAGED_CONNECTION_POOL_CREATE,
                                      "NONE"));
   }
1257764
public static ConnectionPool newBlockingConnectionPool(final AbstractLdapProperties l) {
        final DefaultConnectionFactory bindCf = newConnectionFactory(l);
        final PoolConfig pc = newPoolConfig(l);
        final BlockingConnectionPool cp = new BlockingConnectionPool(pc, bindCf);

        cp.setBlockWaitTime(newDuration(l.getBlockWaitTime()));
        cp.setPoolConfig(pc);

        final IdlePruneStrategy strategy = new IdlePruneStrategy();
        strategy.setIdleTime(newDuration(l.getIdleTime()));
        strategy.setPrunePeriod(newDuration(l.getPrunePeriod()));

        cp.setPruneStrategy(strategy);
        cp.setValidator(new SearchValidator());
        cp.setFailFastInitialize(l.isFailFast());

        if (CommonHelper.isNotBlank(l.getPoolPassivator())) {
            final AbstractLdapProperties.LdapConnectionPoolPassivator pass =
                    AbstractLdapProperties.LdapConnectionPoolPassivator.valueOf(l.getPoolPassivator().toUpperCase());
            switch (pass) {
                case CLOSE:
                    cp.setPassivator(new ClosePassivator());
                    break;
                case BIND:
                    LOGGER.debug("Creating a bind passivator instance for the connection pool");
                    final BindRequest bindRequest = new BindRequest();
                    bindRequest.setDn(l.getBindDn());
                    bindRequest.setCredential(new Credential(l.getBindCredential()));
                    cp.setPassivator(new BindPassivator(bindRequest));
                    break;
                default:
                    break;
            }
        }

        LOGGER.debug("Initializing ldap connection pool for {} and bindDn {}", l.getLdapUrl(), l.getBindDn());
        cp.initialize();
        return cp;
    }
985893
@Override
    protected Object createPoolOrConnection()
    {
        // AuthInfoProvider,LoadBalancingPolicy, ReconnectionPolicy,
        // RetryPolicy,ProtocolOptions.Compression, SSLOptions,
        // PoolingOptions,SocketOptions

        if (logger.isDebugEnabled())
        {
            logger.debug("Intiatilzing connection");
        }

        Properties connectionProperties = CassandraPropertyReader.csmd.getConnectionProperties();
        Builder connectionBuilder = Cluster.builder();

        // add host/port and AuthInfoProvider
        for (Host host : configuration.getCassandraHosts())
        {
            connectionBuilder.addContactPoint(host.getHost()).withPort(host.getPort());
            if (host.getUser() != null)
            {
                connectionBuilder.withCredentials(host.getUser(), host.getPassword());
            }
        }

        // add policy configuration
        String loadBalancingPolicy = connectionProperties.getProperty(Constants.LOADBALANCING_POLICY);
        if (!StringUtils.isBlank(loadBalancingPolicy))
        {
            LoadBalancingPolicy policy = getPolicyInstance(BalancingPolicy.getPolicy(loadBalancingPolicy),
                    connectionProperties);
            if (policy != null)
            {
                connectionBuilder.withLoadBalancingPolicy(policy);
            }
        }

        // compression
        String compression = connectionProperties.getProperty("compression");

        if (!StringUtils.isBlank(compression))
        {
            connectionBuilder.withCompression(Compression.valueOf(compression));
        }

        // ReconnectionPolicy

        String reconnectionPolicy = connectionProperties.getProperty("reconnection.policy");
        if (!StringUtils.isBlank(reconnectionPolicy))
        {
            com.datastax.driver.core.policies.ReconnectionPolicy policy = getPolicy(
                    ReconnectionPolicy.getPolicy(reconnectionPolicy), connectionProperties);

            if (policy != null)
            {
                connectionBuilder.withReconnectionPolicy(policy);
            }

        }

        // , RetryPolicy
        String retryPolicy = connectionProperties.getProperty("retry.policy");

        if (!StringUtils.isBlank(retryPolicy))
        {
            com.datastax.driver.core.policies.RetryPolicy policy = getPolicy(RetryPolicy.getPolicy(retryPolicy),
                    connectionProperties);

            if (policy != null)
            {
                connectionBuilder.withRetryPolicy(policy);
            }

        }

        // TODO::: SSLOptions? Not sure how to add it.

        // SocketOptions
        connectionBuilder.withSocketOptions(getSocketOptions(connectionProperties));

        // PoolingOptions,
        connectionBuilder.withPoolingOptions(getPoolingOptions(connectionProperties));

        // finally build cluster.
        Cluster cluster = connectionBuilder.build();

        PersistenceUnitMetadata persistenceUnitMetadata = kunderaMetadata.getApplicationMetadata()
                .getPersistenceUnitMetadata(getPersistenceUnit());
        Properties props = persistenceUnitMetadata.getProperties();

        if (externalProperties != null)
        {
            keyspace = (String) externalProperties.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }

        if (keyspace == null)
        {
            keyspace = (String) props.get(PersistenceProperties.KUNDERA_KEYSPACE);
        }
        setSessionObject(cluster); // TODO custom session
        return cluster; // TODO custom cluster
    }
186623
public static ShardedJedisPool newShardedJedisPool(JedisPoolConfig poolConfig,
            String hostsAndPorts) {
        return newShardedJedisPool(poolConfig, hostsAndPorts, null, Protocol.DEFAULT_TIMEOUT);
    }