Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Distributed Cache Service/ Best Practices/ Usage Guide/ Optimizing the Jedis Connection Pool

Optimizing the Jedis Connection Pool

Updated on 2024-12-31 GMT+08:00

Overview

JedisPool is the connection pool of the Jedis client. This section describes how to configure JedisPool for better Redis performance and resource utilization.

Using JedisPool

The following Maven dependency is for Jedis 5.1.3.

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.3</version>
</dependency>

Jedis manages resource pools using Apache Commons-pool2. The key parameter GenericObjectPoolConfig (resource pool) is required to define JedisPool. This parameter can be used as follows. For details, see JedisPool Parameters.

GenericObjectPoolConfig jedisPoolConfig = new GenericObjectPoolConfig();
jedisPoolConfig.setMaxTotal(...);
jedisPoolConfig.setMaxIdle(...);
jedisPoolConfig.setMinIdle(...);
jedisPoolConfig.setMaxWaitMillis(...);

JedisPool is initialized as follows:

// redisHost is the IP address of the Redis instance. redisPort is the port of the Redis instance. redisPassword is the password of the Redis instance. timeout is the connection or read/write timeout.
JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, redisPort, timeout, redisPassword);

// Execution
Jedis jedis = null;
try {
    jedis = jedisPool.getResource();
    // Specific command
    jedis.set("key", "value");
} catch (Exception e) {
    logger.error(e.getMessage(), e);
} finally {
    // With JedisPool, Jedis connections will be returned to the resource pool.
    if (jedis != null) 
        jedis.close();
}

JedisPool Parameters

JedisPool manages Jedis connections in a connection pool, which ensures resource control and thread security. GenericObjectPoolConfig can improve Redis performance at lower costs. Table 1 and Table 2 describe parameters and their configuration suggestions.

Table 1 Parameters related to resource configuration and utilization

Parameter

Description

Default Value

Suggestion

maxTotal

Maximum number of connections in a resource pool

8

Suggestions on Key Parameters

maxIdle

Maximum number of idle connections allowed in a resource pool

8

Suggestions on Key Parameters

minIdle

Minimum number of idle connections allowed in a resource pool

0

Suggestions on Key Parameters

blockWhenExhausted

Whether a caller awaits when a resource pool is used up

  • true: yes
  • false: no

maxWaitMillis is valid only when this parameter is set to true.

true

Use the default value.

maxWaitMillis

Maximum time that a caller waits after a resource pool is used up, in milliseconds.

The value -1 indicates that the caller keeps waiting.

-1

Specify a time.

testOnBorrow

Whether to test validity of connections borrowed from a resource pool (ping). Invalid connections will be removed.

  • true: yes
  • false: no

false

Set to false during heavy service hours, saving resources a ping.

testOnReturn

Whether to test validity of connections returned to a resource pool (ping). Invalid connections will be removed.

  • true: yes
  • false: no

false

Set to false during heavy service hours, saving resources a ping.

jmxEnabled

Whether to enable JMX monitoring.

  • true: yes
  • false: no

true

Enable it, also for the application.

Table 2 describes the parameters for testing idle Jedis objects.

Table 2 Idle resource testing parameters

Parameter

Description

Default Value

Suggestion

testWhileIdle

Whether to test validity of idle connections using ping. Invalid ones will be destroyed.

false

true

timeBetweenEvictionRunsMillis

Interval of looking for idle resources, in milliseconds.

-1: disabled

-1

Specify an interval, use the default value, or use the JedisPoolConfig.

minEvictableIdleTimeMillis

Minimum idle duration in a resource pool, in milliseconds. Resources that are idle longer than this will be removed.

1,800,000 (30 minutes)

Specify it as required. Generally, use the default value. JedisPoolConfig can be used.

numTestsPerEvictionRun

Number of idle resources to be tested each time.

3

Adjust this parameter as required. The value -1 indicates that all idle connections are tested.

Jedis provides JedisPoolConfig which inherits certain idle connection testing settings of GenericObjectPoolConfig.

public class JedisPoolConfig extends GenericObjectPoolConfig {
  public JedisPoolConfig() {
    setTestWhileIdle(true);
    setMinEvictableIdleTimeMillis(60000);
    setTimeBetweenEvictionRunsMillis(30000);
    setNumTestsPerEvictionRun(-1);
    }}
NOTE:

All of the default values are available in org.apache.commons.pool2.impl.BaseObjectPoolConfig.

Suggestions on Key Parameters

  • maxTotal

    Consider the following factors:

    Assume that the average duration of executing a command is 1 ms. This execution covers the resource borrowing and returning, and network transmission. The QPS of a connection is about 1000 (1s/1 ms). The expected QPS per instance is 50,000 (Total service QPS/Number of Redis shards). Ideally, the required resource pool size (maxTotal) is 50 (50,000/1000).

    In reality, more resources need to be reserved. Therefore, maxTotal can be greater. However, a large maxTotal allows many connections, which consume client and server resources. Furthermore, large commands with high QPS may block Redis and a large resource pool does not work.

  • maxIdle and minIdle

    maxIdle is the maximum number of connections required by services. maxTotal reserves resources. Do not use tiny maxIdle. Otherwise, new connection overhead occurs. minIdle controls idle resource testing.

    Setting maxIdle to the same as maxTotal achieves an optimal connection pool and avoids performance impact caused by connection pool scaling. This combination fits in peak service hours, but causes resource wastes when the number of concurrent connections is small or maxIdle is excessively high.

    The connection pool size of a node can be estimated based on the total QPS and the client scale.

  • Using monitoring for appropriate values

    In actual environments, an optimal parameter can be obtained through monitoring, such as JMX.

Common Errors

  • Insufficient resources

    The following two cases indicate that resources cannot be obtained from the pool. This is not necessarily due to small resource pools (see Suggestions on Key Parameters). The network, resource pool parameter settings, resource pool monitoring (JMX), code (for example, jedis.close() is not executed), slow queries, and DNS may also be the cause.

    1. Timeout:
      redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
      ...Caused by: java.util.NoSuchElementException: Timeout waiting for idle object
      at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject
    2. When a resource pool is used up, it does not wait for resource release if blockWhenExhausted is set to false:
      redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
      ...Caused by: java.util.NoSuchElementException: Pool exhausted
      at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject
  • JedisPool preheating

    A project may time out after start for some reasons (for example, small timeout interval). When the maximum number of resources and minimum number of idle resources are defined by JedisPool, Jedis connections are not created in the connection pool. In initial use, if no resource in the pool is used, a new Jedis connection is created and then added to the resource pool. This process takes some time. Therefore, you are advised to preheat JedisPool based on the minimum number of idle connections after defining JedisPool. The following is an example:

    List<Jedis> minIdleJedisList = new ArrayList<Jedis>(jedisPoolConfig.getMinIdle());
    for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            minIdleJedisList.add(jedis);
            jedis.ping();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
        }
    }
    for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
        Jedis jedis = null;
        try {
            jedis = minIdleJedisList.get(i);
            jedis.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
        
        }
    }

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback