tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Java Connection Sample

Download
Focus Mode
Font Size
Last updated: 2026-09-07 14:31:32
AI-Translated
This document provides an example of using a Java client to connect to a Tencent Cloud Distributed Cache instance.

Preparations

Environment Requirement

JDK 8 or later.
Maven or Gradle build tool.

Adding Dependencies

Maven Dependency
<!-- Jedis client (version 5.1.2 or later recommended) -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>5.1.2</version>
</dependency>

<!-- Lettuce client (version 6.3.0 or later recommended) -->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.3.0.RELEASE</version>
</dependency>
Gradle Dependency
implementation 'redis.clients:jedis:5.1.2'
implementation 'io.lettuce:lettuce-core:6.3.0.RELEASE'

Obtaining Connection Information

1. Log in to the Distributed Cache console.
2. In the instance list, click the target instance ID to go to the instance details page.
3. In the Network Information section, obtain the instance's VIP address and port (default is 6379).
4. In the Configuration Information section, obtain the connection password for the instance.
Default accounts use the Instance ID:Password format, and custom accounts use the Username@Password format. Instances with password-free authentication do not require a password.

Connection Example

In proxy mode, clients connect to an instance through the unified VIP address provided by the Proxy layer. Proxy automatically handles request routing and failover, so clients do not need to be aware of backend topology changes.
Note:
Multi-DB Usage Notes: In proxy mode, the server supports multiple DBs (256 DBs are allocated by default). However, due to implementation limitations, Jedis may not be able to use the SELECT command to switch databases, in which case only DB0 can be used. If your business depends on multiple DBs, switch to a client that supports the SELECT command.

Jedis Connection Pool Example (Recommended)

Use JedisPool to manage connections. It is recommended to configure FIFO mode to avoid uneven load distribution.
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Jedis;

public class JedisProxyExample {
public static void main(String[] args) {
// Connection parameters
String host = "192.xx.xx.2"; // Instance VIP address
int port = 6379; // Instance port
String password = "crs-xxxx:password"; // Default account password format: Instance ID:Password

// Connection pool configuration
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200); // Maximum number of connections
poolConfig.setMaxIdle(200); // Maximum number of idle connections
poolConfig.setMinIdle(50); // Minimum number of idle connections
poolConfig.setMaxWaitMillis(3000); // Maximum wait time to obtain a connection (in milliseconds)
poolConfig.setTestOnBorrow(false); // Do not test when obtaining a connection
poolConfig.setTestOnReturn(false); // Do not test when returning a connection
poolConfig.setTestWhileIdle(true); // Test connection validity when idle
poolConfig.setLifo(false); // Disable LIFO and use FIFO to avoid uneven load distribution

// Create a connection pool
JedisPool jedisPool = new JedisPool(
poolConfig,
host,
port,
2000, // Connection timeout (in milliseconds)
2000, // Read timeout (in milliseconds)
password
);

// Use a connection pool to perform operations
try (Jedis jedis = jedisPool.getResource()) {
// Write data.
jedis.set("name", "Distributed Cache");
// Read data.
String value = jedis.get("name");
System.out.println("get name: " + value);

// Set a Key with an expiration time.
jedis.setex("session:user123", 3600, "session_data");

// Hash operations
jedis.hset("user:1001", "name", "Zhang San");
jedis.hset("user:1001", "age", "28");
System.out.println("user name: " + jedis.hget("user:1001", "name"));

// List operations
jedis.lpush("queue:tasks", "task1", "task2", "task3");
String task = jedis.rpop("queue:tasks");
System.out.println("dequeued task: " + task);
}

// Destroy the connection pool when the application shuts down.
jedisPool.close();
}
}

Jedis Custom Account Connection Example

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Jedis;

public class JedisCustomAccountExample {
public static void main(String[] args) {
String host = "192.xx.xx.2";
int port = 6379;
String password = "myuser@MyPassword"; // Custom account in proxy mode: the entire "username@password" string is passed as the password.

JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(200);
poolConfig.setMinIdle(50);
poolConfig.setLifo(false);

// Custom account in proxy mode: pass the entire "username@password" string as the password without setting the username separately.
JedisPool jedisPool = new JedisPool(
poolConfig,
host,
port,
2000,
2000,
password // username@password
);

try (Jedis jedis = jedisPool.getResource()) {
jedis.set("key", "value");
System.out.println(jedis.get("key"));
}

jedisPool.close();
}
}

Spring Boot + Jedis Integration Example

application.yml configuration
spring:
redis:
host: 192.xx.xx.2
port: 6379
password: crs-xxxx:password
timeout: 2000ms
jedis:
pool:
max-active: 200
max-idle: 200
min-idle: 50
max-wait: 3000ms
Configuration class
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 org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

@Configuration
public class RedisConfig {

@Bean
public JedisConnectionFactory jedisConnectionFactory() {
// Standalone configuration
RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration();
standaloneConfig.setHostName("192.xx.xx.2");
standaloneConfig.setPort(6379);
standaloneConfig.setPassword("crs-xxxx:password");

// Connection pool configuration
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(200);
poolConfig.setMinIdle(50);
poolConfig.setMaxWaitMillis(3000);
poolConfig.setLifo(false); // FIFO mode

// Client configuration
JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
.connectTimeout(Duration.ofMillis(2000))
.readTimeout(Duration.ofMillis(2000))
.usePooling()
.poolConfig(poolConfig)
.build();

return new JedisConnectionFactory(standaloneConfig, clientConfig);
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}

Lettuce Connection Example (Recommended)

Lettuce is an asynchronous Redis client built on Netty. Use version 6.3.0 or later, and configure the TCP Keepalive and tcpUserTimeout parameters.
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.core.support.ConnectionPoolSupport;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.time.Duration;

public class LettuceProxyExample {
public static void main(String[] args) {
// Build a RedisURI
RedisURI redisUri = RedisURI.builder()
.withHost("192.xx.xx.2")
.withPort(6379)
.withPassword("crs-xxxx:password".toCharArray())
.withTimeout(Duration.ofSeconds(2))
.build();

// Socket configuration (key parameters)
SocketOptions socketOptions = SocketOptions.builder()
.connectTimeout(Duration.ofSeconds(2)) // Connection timeout
.keepAlive(SocketOptions.KeepAliveOptions.builder()
.enable() // Enable TCP Keepalive
.idle(Duration.ofSeconds(30)) // Start probing after 30 seconds of idle time
.interval(Duration.ofSeconds(10)) // Probing interval: 10 seconds
.count(3) // Number of probes: 3
.build())
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
.enable() // Enable tcpUserTimeout
.tcpUserTimeout(Duration.ofSeconds(30)) // 30-second timeout
.build())
.build();

// Create a RedisClient
RedisClient redisClient = RedisClient.create();
redisClient.setOptions(io.lettuce.core.ClientOptions.builder()
.socketOptions(socketOptions)
.build());

// Connection pool configuration
GenericObjectPoolConfig<StatefulRedisConnection<String, String>> poolConfig =
new GenericObjectPoolConfig<>();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(200);
poolConfig.setMinIdle(50);
poolConfig.setMaxWaitMillis(3000);
poolConfig.setLifo(false); // FIFO mode

// Create a connection pool
GenericObjectPool<StatefulRedisConnection<String, String>> pool =
ConnectionPoolSupport.createGenericObjectPool(
() -> redisClient.connect(redisUri),
poolConfig
);

// Use a connection pool to perform operations
try (StatefulRedisConnection<String, String> connection = pool.borrowObject()) {
RedisCommands<String, String> sync = connection.sync();
sync.set("name", "Distributed Cache");
String value = sync.get("name");
System.out.println("get name: " + value);

sync.hset("user:1001", "name", "Zhang San");
sync.hset("user:1001", "age", "28");
System.out.println("user name: " + sync.hget("user:1001", "name"));
} catch (Exception e) {
e.printStackTrace();
}

// Clean up resources when the application shuts down.
pool.close();
redisClient.shutdown();
}
}

Spring Boot + Lettuce Integration Example

application.yml configuration
spring:
redis:
host: 192.xx.xx.2
port: 6379
password: crs-xxxx:password
timeout: 2000ms
lettuce:
pool:
max-active: 200
max-idle: 200
min-idle: 50
max-wait: 3000ms
Configuration class (including TCP Keepalive and tcpUserTimeout)
import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
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.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.time.Duration;

@Configuration
public class LettuceRedisConfig {

@Bean(destroyMethod = "shutdown")
public ClientResources clientResources() {
return DefaultClientResources.create();
}

@Bean
public LettuceConnectionFactory lettuceConnectionFactory(ClientResources clientResources) {
// Socket configuration
SocketOptions socketOptions = SocketOptions.builder()
.connectTimeout(Duration.ofSeconds(2))
.keepAlive(SocketOptions.KeepAliveOptions.builder()
.enable()
.idle(Duration.ofSeconds(30))
.interval(Duration.ofSeconds(10))
.count(3)
.build())
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
.enable()
.tcpUserTimeout(Duration.ofSeconds(30))
.build())
.build();

ClientOptions clientOptions = ClientOptions.builder()
.socketOptions(socketOptions)
.build();

// Connection pool configuration
GenericObjectPoolConfig<?> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(200);
poolConfig.setMinIdle(50);
poolConfig.setMaxWaitMillis(3000);
poolConfig.setLifo(false);

// Lettuce client configuration
LettucePoolingClientConfiguration lettuceConfig =
LettucePoolingClientConfiguration.builder()
.commandTimeout(Duration.ofSeconds(2))
.clientOptions(clientOptions)
.clientResources(clientResources)
.poolConfig(poolConfig)
.build();

// Create a connection factory.
org.springframework.data.redis.connection.RedisStandaloneConfiguration standaloneConfig =
new org.springframework.data.redis.connection.RedisStandaloneConfiguration();
standaloneConfig.setHostName("192.xx.xx.2");
standaloneConfig.setPort(6379);
standaloneConfig.setPassword("crs-xxxx:password");

return new LettuceConnectionFactory(standaloneConfig, lettuceConfig);
}

@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}

SSL Encryption Connection Example (Jedis)

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Jedis;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

public class JedisSSLExample {
public static void main(String[] args) throws Exception {
String host = "192.xx.xx.2";
int port = 6379;
String password = "crs-xxxx:password";

// Load the CA certificate (JKS format).
KeyStore trustStore = KeyStore.getInstance("JKS");
try (FileInputStream fis = new FileInputStream("/path/to/ca.jks")) {
trustStore.load(fis, "password".toCharArray());
}

TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);

// Connection pool configuration
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(200);
poolConfig.setMaxIdle(200);
poolConfig.setMinIdle(50);
poolConfig.setLifo(false);

// Create an SSL connection pool.
JedisPool jedisPool = new JedisPool(
poolConfig,
host,
port,
2000,
2000,
password,
true, // Enable SSL.
sslContext.getSocketFactory(),
null, // SSL parameter
null // Hostname verifier
);

try (Jedis jedis = jedisPool.getResource()) {
jedis.set("ssl_test", "encrypted");
System.out.println(jedis.get("ssl_test"));
}

jedisPool.close();
}
}

Key Parameter Description

Jedis Connection Pool Parameters

Parameter
Description
Recommended Value
maxTotal
Maximum Number of Connections
200
maxIdle
Maximum number of idle connections.
200
minIdle
Minimum number of free connections.
50
maxWaitMillis
Maximum wait time for obtaining a connection (ms).
3000
lifo
Connection acquisition policy
false (FIFO to prevent uneven load distribution)
connectTimeout
Connection timeout (ms)
2000
readTimeout
Read timeout (ms)
2000

Lettuce TCP Keepalive Parameters

Parameter
Description
Recommended Value
keepAlive.idle
Idle duration before probing starts
30 seconds
keepAlive.interval
Probing interval.
10 seconds
keepAlive.count
Number of Probings.
3 times
tcpUserTimeout
TCP user timeout
30 seconds
Note:
TCP Keepalive and tcpUserTimeout are required configurations for connecting to Distributed Cache:
TCP Keepalive: During a primary-secondary switch, the VIP drifts and existing connections become dead. If Keepalive is not enabled, the client cannot detect the connection interruption, causing request timeouts.
tcpUserTimeout: When a node goes down passively, the TCP connection cannot be closed normally. If tcpUserTimeout is not set, zombie connections will continue to occupy resources for more than 30 minutes.

FAQs

Connection Timeout

Confirm that the CVM where the client resides and the Distributed Cache instance are in the same VPC.
Confirm that the security group rule allows access to the corresponding port.
Confirm that the connection address and port are correct.

Lettuce Connection Pool Connection Acquisition Timeout

Check whether maxTotal and maxIdle are set appropriately.
Confirm that lifo is set to false (FIFO mode).
Confirm that minIdle is set appropriately to avoid the overhead of cold connection establishment.

Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback