Connecting to Redis on Jedis (Java)
This section describes how to access a DCS Redis instance on Jedis. For more information about how to use other Redis clients, visit the Redis official website.
In Spring Boot projects, Spring Data Redis has been already integrated with Jedis and Lettuce. Spring Boot 1.x is integrated with Jedis, and Spring Boot 2.x is integrated with Lettuce by default. To use Jedis in Spring Boot 2.x or later, you need to exclude the Lettuce dependency.
Notes and Constraints
Spring Boot must be 2.3.12.RELEASE or later, and Jedis must be 3.10.0 or later.
To access a Redis 7.0 instance, use a Jedis 5.0.0 client or later. Jedis 5.1.1 and later versions are recommended.
Prerequisites
- A Redis instance is created, and is in the Running state. To create a Redis instance, see Buying a DCS Redis Instance.
- You have obtained the IP address/domain name and port number of the target Redis instance. For details, see Viewing and Modifying Basic Information About a DCS Instance. To access Redis on a client over a public network, obtain the public IP address and port number by referring to Enabling Public Access to Redis and Obtaining the Access Addresses.
- Connectivity between the client and the Redis instance has been established. For details, see Network Conditions for Accessing DCS Redis.
Pom Configuration
<!-- import spring-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!--Lettuce is used by default since Spring Boot 2.0. To use Jedis, exclude Lettuce dependency.-->
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- import Jedis dependency -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency> Configuration Based on the application.properties File
The configuration varies depending on the Spring Boot version. The following are the configurations for Spring Boot 2.x and Spring Boot 3.x.
- Configuration for single-node, master/standby, read/write splitting, and Proxy Cluster instances
# Redis host spring.redis.host=<host> # Redis port spring.redis.port=<port> # Redis database index spring.redis.database=0 # Redis password spring.redis.password=<password> # Redis read/write timeout spring.redis.timeout=2000 # Whether to enable the connection pool spring.redis.jedis.pool.enabled=true # Minimum number of connections in the connection pool spring.redis.jedis.pool.min-idle=50 # Maximum number of idle connections in the connection pool spring.redis.jedis.pool.max-idle=200 # Maximum number of connections in the connection pool spring.redis.jedis.pool.max-active=200 # Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. spring.redis.jedis.pool.max-wait=3000 # Interval for checking and evicting idle connections. The default value is 60s. spring.redis.jedis.pool.time-between-eviction-runs=60s
- Configuration for Cluster instances
# Redis Cluster node connection information spring.redis.cluster.nodes=<ip:port>,<ip:port>,<ip:port> # Redis Cluster password spring.redis.password=<password> # Maximum number of Redis Cluster redirections spring.redis.cluster.max-redirects=3 # Redis read/write timeout spring.redis.timeout=2000 # Whether to enable the connection pool spring.redis.jedis.pool.enabled=true # Minimum number of connections in the connection pool spring.redis.jedis.pool.min-idle=50 # Maximum number of idle connections in the connection pool spring.redis.jedis.pool.max-idle=200 # Maximum number of connections in the connection pool spring.redis.jedis.pool.max-active=200 # Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. spring.redis.jedis.pool.max-wait=3000 # Interval for checking and evicting idle connections. The default value is 60s. spring.redis.jedis.pool.time-between-eviction-runs=60s
- Configuration for single-node, master/standby, read/write splitting, and Proxy Cluster instances
#redis host spring.data.redis.host=<host> # Redis port spring.data.redis.port=<port> # Redis database index spring.data.redis.database=0 # Redis password spring.data.redis.password=<password> # Redis read/write timeout spring.data.redis.timeout=2000 # Whether to enable the connection pool spring.data.redis.jedis.pool.enabled=true # Minimum number of connections in the connection pool spring.data.redis.jedis.pool.min-idle=50 # Maximum number of idle connections in the connection pool spring.data.redis.jedis.pool.max-idle=200 # Maximum number of connections in the connection pool spring.data.redis.jedis.pool.max-active=200 # Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. spring.data.redis.jedis.pool.max-wait=3000 # Interval for checking and evicting idle connections. The default value is 60s. spring.data.redis.jedis.pool.time-between-eviction-runs=60s
- Configuration for Cluster instances
# Redis Cluster node connection information spring.data.redis.cluster.nodes=<ip:port>,<ip:port>,<ip:port> # Redis Cluster password spring.data.redis.password=<password> # Maximum number of Redis Cluster redirections spring.data.redis.cluster.max-redirects=3 # Redis read/write timeout spring.data.redis.timeout=2000 # Whether to enable the connection pool spring.data.redis.jedis.pool.enabled=true # Minimum number of connections in the connection pool spring.data.redis.jedis.pool.min-idle=50 # Maximum number of idle connections in the connection pool spring.data.redis.jedis.pool.max-idle=200 # Maximum number of connections in the connection pool spring.data.redis.jedis.pool.max-active=200 # Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. spring.data.redis.jedis.pool.max-wait=3000 # Interval for checking and evicting idle connections. The default value is 60s. spring.data.redis.jedis.pool.time-between-eviction-runs=60s
Bean-based Configuration
- Configuration for single-node, master/standby, read/write splitting, and Proxy Cluster instances
import java.time.Duration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import redis.clients.jedis.JedisPoolConfig; @Configuration public class RedisConfiguration { @Value("${redis.host}") private String redisHost; @Value("${redis.port:6379}") private Integer redisPort = 6379; @Value("${redis.database:0}") private Integer redisDatabase = 0; @Value("${redis.password:}") private String redisPassword; @Value("${redis.connect.timeout:3000}") private Integer redisConnectTimeout = 3000; @Value("${redis.read.timeout:2000}") private Integer redisReadTimeout = 2000; @Value("${redis.pool.minSize:50}") private Integer redisPoolMinSize = 50; @Value("${redis.pool.maxSize:200}") private Integer redisPoolMaxSize = 200; @Value("${redis.pool.maxWaitMillis:3000}") private Integer redisPoolMaxWaitMillis = 3000; @Value("${redis.pool.softMinEvictableIdleTimeMillis:1800000}") private Integer redisPoolSoftMinEvictableIdleTimeMillis = 30 * 60 * 1000; @Value("${redis.pool.timeBetweenEvictionRunsMillis:60000}") private Integer redisPoolBetweenEvictionRunsMillis = 60 * 1000; @Bean public RedisConnectionFactory redisConnectionFactory(JedisClientConfiguration clientConfiguration) { RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration(); standaloneConfiguration.setHostName(redisHost); standaloneConfiguration.setPort(redisPort); standaloneConfiguration.setDatabase(redisDatabase); standaloneConfiguration.setPassword(redisPassword); return new JedisConnectionFactory(standaloneConfiguration, clientConfiguration); } @Bean public JedisClientConfiguration clientConfiguration() { JedisClientConfiguration clientConfiguration = JedisClientConfiguration.builder() .connectTimeout(Duration.ofMillis(redisConnectTimeout)) .readTimeout(Duration.ofMillis(redisReadTimeout)) .usePooling().poolConfig(redisPoolConfig()) .build(); return clientConfiguration; } private JedisPoolConfig redisPoolConfig() { JedisPoolConfig poolConfig = new JedisPoolConfig(); // Minimum number of connections in the connection pool poolConfig.setMinIdle(redisPoolMinSize); // Maximum number of idle connections in the connection pool poolConfig.setMaxIdle(redisPoolMaxSize); // Maximum number of connections in the connection pool poolConfig.setMaxTotal(redisPoolMaxSize); // Whether to wait for an available connection when the connection pool is exhausted. The default value true indicates to wait. setMaxWait takes effect only when the value is true. poolConfig.setBlockWhenExhausted(true); // Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. poolConfig.setMaxWaitMillis(redisPoolMaxWaitMillis); // Whether to validate a new connection using a ping command after it is created. The default value is false. poolConfig.setTestOnCreate(false); // Whether to validate a connection using a ping command every time a connection is borrowed from the pool. The default value is false. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. poolConfig.setTestOnBorrow(true); // Whether to validate a connection using a ping command every time a connection is returned to the pool. The default value is false. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. poolConfig.setTestOnReturn(false); // Whether to check for idle connections. If the value is false, idle connections are not evicted. poolConfig.setTestWhileIdle(true); // Duration after which an idle connection is evicted. If the actual idle duration of a connection is greater than this value and the number of idle connections is greater than the minimum number of idle connections, the connection is directly evicted. poolConfig.setSoftMinEvictableIdleTimeMillis(redisPoolSoftMinEvictableIdleTimeMillis); // Disable eviction of idle connections based on MinEvictableIdleTimeMillis. poolConfig.setMinEvictableIdleTimeMillis(-1); // Interval for checking and evicting idle connections. The default value is 60s. poolConfig.setTimeBetweenEvictionRunsMillis(redisPoolBetweenEvictionRunsMillis); return poolConfig; } } - Configuration for Cluster instances
import java.time.Duration; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisNode; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import redis.clients.jedis.JedisPoolConfig; @Configuration public class RedisConfiguration { @Value("${redis.cluster.nodes}") private String redisClusterNodes; @Value("${redis.password:}") private String redisPassword; @Value("${redis.connect.timeout:3000}") private Integer redisConnectTimeout = 3000; @Value("${redis.read.timeout:2000}") private Integer redisReadTimeout = 2000; @Value("${redis.pool.minSize:50}") private Integer redisPoolMinSize = 50; @Value("${redis.pool.maxSize:200}") private Integer redisPoolMaxSize = 200; @Value("${redis.pool.maxWaitMillis:3000}") private Integer redisPoolMaxWaitMillis = 3000; @Value("${redis.pool.softMinEvictableIdleTimeMillis:1800000}") private Integer redisPoolSoftMinEvictableIdleTimeMillis = 30 * 60 * 1000; @Value("${redis.pool.timeBetweenEvictionRunsMillis:60000}") private Integer redisPoolBetweenEvictionRunsMillis = 60 * 1000; @Bean public RedisConnectionFactory redisConnectionFactory(JedisClientConfiguration clientConfiguration) { RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration(); List<RedisNode> clusterNodes = new ArrayList<>(); for (String clusterNodeStr : redisClusterNodes.split(",")) { String[] nodeInfo = clusterNodeStr.split(":"); clusterNodes.add(new RedisNode(nodeInfo[0], Integer.valueOf(nodeInfo[1]))); } clusterConfiguration.setClusterNodes(clusterNodes); clusterConfiguration.setPassword(redisPassword); clusterConfiguration.setMaxRedirects(3); return new JedisConnectionFactory(clusterConfiguration, clientConfiguration); } @Bean public JedisClientConfiguration clientConfiguration() { JedisClientConfiguration clientConfiguration = JedisClientConfiguration.builder() .connectTimeout(Duration.ofMillis(redisConnectTimeout)) .readTimeout(Duration.ofMillis(redisReadTimeout)) .usePooling().poolConfig(redisPoolConfig()) .build(); return clientConfiguration; } private JedisPoolConfig redisPoolConfig() { JedisPoolConfig poolConfig = new JedisPoolConfig(); // Minimum number of connections in the connection pool poolConfig.setMinIdle(redisPoolMinSize); // Maximum number of idle connections in the connection pool poolConfig.setMaxIdle(redisPoolMaxSize); // Maximum number of connections in the connection pool poolConfig.setMaxTotal(redisPoolMaxSize); // Whether to wait for an available connection when the connection pool is exhausted. The default value true indicates to wait. setMaxWait takes effect only when the value is true. poolConfig.setBlockWhenExhausted(true); // Maximum wait time for obtaining a connection from the pool when the pool is exhausted. The default value -1 indicates to wait indefinitely for a connection to become available. poolConfig.setMaxWaitMillis(redisPoolMaxWaitMillis); // Whether to validate a new connection using a ping command after it is created. The default value is false. poolConfig.setTestOnCreate(false); // Whether to validate a connection using a ping command every time a connection is borrowed from the pool. The default value is false. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. poolConfig.setTestOnBorrow(true); // Whether to validate a connection using a ping command every time a connection is returned to the pool. The default value is false. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. poolConfig.setTestOnReturn(false); // Whether to check for idle connections. If the value is false, idle connections are not evicted. poolConfig.setTestWhileIdle(true); // Duration after which an idle connection is evicted. If the actual idle duration of a connection is greater than this value and the number of idle connections is greater than the minimum number of idle connections, the connection is directly evicted. poolConfig.setSoftMinEvictableIdleTimeMillis(redisPoolSoftMinEvictableIdleTimeMillis); // Disable eviction of idle connections based on MinEvictableIdleTimeMillis. poolConfig.setMinEvictableIdleTimeMillis(-1); // Interval for checking and evicting idle connections. The default value is 60s. poolConfig.setTimeBetweenEvictionRunsMillis(redisPoolBetweenEvictionRunsMillis); return poolConfig; } }
(Optional) SSL Connection Configuration
If SSL is enabled for the instance, use the following content to replace the JedisClientConfiguration constructor clientConfiguration() in Bean-based Configuration for connecting to the instance via SSL. For details about whether your Redis instances support SSL, see Transmitting DCS Redis Data with SSL Encryption.
@Bean
public JedisClientConfiguration clientConfiguration() throws Exception {
JedisClientConfiguration.JedisClientConfigurationBuilder configurationBuilder
= JedisClientConfiguration.builder()
.connectTimeout(Duration.ofMillis(redisConnectTimeout))
.readTimeout(Duration.ofMillis(redisReadTimeout));
configurationBuilder.usePooling().poolConfig(redisPoolConfig());
configurationBuilder.useSsl().sslSocketFactory(getTrustStoreSslSocketFactory());
return configurationBuilder.build();
}
private SSLSocketFactory getTrustStoreSslSocketFactory() throws Exception{
// Load the CA certificate in the user-defined path based on service requirements.
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream is = new FileInputStream("./ca.crt")) {
ca = cf.generateCertificate(is);
}
// Create a keystore.
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create TrustManager.
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
// Create SSLContext.
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return context.getSocketFactory();
} Parameters
| Parameter | Default Value | Description |
|---|---|---|
| hostName | localhost | IP address/domain name for connecting to a DCS Redis instance. |
| port | 6379 | Port number for setting up the connection. |
| database | 0 | Database index. The default value is 0. |
| password | - | Password for connecting to a DCS Redis instance. If password-free access is enabled for the instance, you do not need to enter the password. If you forget the password or need to reset it, see Resetting an Instance Password.
|
| Parameter | Description |
|---|---|
| clusterNodes | Cluster node connection information, including the node IP address and port number. |
| maxRedirects | Maximum number of Cluster redirections. |
| password | Password for connecting to a DCS Redis instance. If password-free access is enabled for the instance, you do not need to enter the password. If you forget the password or need to reset it, see Resetting an Instance Password.
|
| Parameter | Default Value | Description |
|---|---|---|
| minIdle | - | Minimum number of connections in the connection pool. |
| maxIdle | - | Maximum number of idle connections in the connection pool. |
| maxTotal | - | Maximum number of connections in the connection pool. |
| blockWhenExhausted | true | Whether to wait for an available connection when the connection pool is exhausted. The default value true indicates to wait, and false indicates not to wait. maxWaitMillis takes effect only when this parameter is set to true. |
| maxWaitMillis | -1 | Maximum wait time for obtaining a connection after the connection pool is exhausted, in milliseconds. The default value -1 indicates to wait indefinitely. |
| testOnCreate | false | Whether to validate a new connection using a ping command after it is created. The value true indicates to validate the connection, and false indicates not to validate it. |
| testOnBorrow | false | Whether to validate a connection using a ping command every time a connection is borrowed from the pool. The value true indicates to validate the connection, and false indicates not to validate it. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. |
| testOnReturn | false | Whether to validate a connection using a ping command every time a connection is returned to the pool. The value true indicates to validate the connection, and false indicates not to validate it. When the service traffic is heavy, you are advised to set this parameter to false to reduce overhead. |
| testWhileIdle | false | Whether to check for idle connections. If the value is false, idle connections are not evicted. The recommended value is true. |
| softMinEvictableIdleTimeMillis | 1800000 | Duration after which an idle connection is evicted, in milliseconds. If the actual idle duration of a connection is greater than this value and the number of idle connections is greater than the minimum number of idle connections, the connection is directly evicted. |
| minEvictableIdleTimeMillis | 60000 | Minimum time a connection may remain idle in the pool before it is eligible for eviction, in milliseconds. The recommended value is -1, indicating that softMinEvictableIdleTimeMillis is used instead. |
| timeBetweenEvictionRunsMillis | 60000 | Interval for checking and evicting idle connections, in milliseconds. |
| Parameter | Default Value | Description |
|---|---|---|
| connectTimeout | 2000 | Connection timeout period, in milliseconds. |
| readTimeout | 2000 | Timeout period for waiting for a response, in milliseconds. |
| poolConfig | - | Pool configurations. For details, see JedisPoolConfig. |
Recommended DCS Instance Configurations
- Connection pool configurations
The following calculation methods apply only to common service scenarios. You can adjust the configurations based on your service requirements.
There is no fixed standard for the size of a connection pool. You are advised to configure the size based on your service traffic. The following formulas are for your reference:
- Minimum number of connections = (QPS for accessing the Redis instance from a single node)/(1000 ms/Average time spent per command)
- Maximum number of connections = (QPS for accessing the Redis instance from a single node)/(1000 ms/Average time spent per command) x 150%
Assume that the QPS of a service application is about 10,000, each request needs to access the Redis instance 10 times (that is, 100,000 access requests to the Redis instance every second), and the service application is running on 10 nodes. The calculation is as follows:
QPS for accessing the Redis instance from a single node = 100,000/10 = 10,000
Average time spent per command = 20 ms (The Redis instance takes 5 ms to 10 ms to process a single command under normal conditions. If network jitter occurs, it takes about 15 ms to 20 ms.)
Minimum number of connections = 10,000/(1000 ms/20 ms) = 200
Maximum number of connections = 10,000/(1000 ms/20 ms) × 150% = 300
What is your overall rating for this page?
Thank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot