tencent cloud

Tencent Cloud Distributed Cache (Redis OSS-Compatible)

Sample Code

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-03-17 18:23:48

Pom Configuration

<!-- Introduce the spring-data-redis component, which integrates the Lettuce dependency SDK by default. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<version>6.3.0.RELEASE</version>
</dependency>

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<version>4.1.100.Final</version>
<classifier>linux-x86_64</classifier>
</dependency>

Configuring Code

Note:
Configure the Lettuce connection pool with LIFO = false (namely, using FIFO queue mode). Otherwise, in a VIP cloud environment, differences in connection response times may cause load imbalances and connection pool failures.
1. By default, the Last-In-First-Out (LIFO) mode preferentially reuses the most recently returned connections, making some fast-responding connections "hot connections", while slow-responding connections remain idle for long periods, causing skewed actual load in the backend.
2. Connection pool failure: When a connection is temporarily abandoned due to slow response, the LIFO mechanism exacerbates the concentration of new requests assigned to a few active connections, amplifying single-point bottleneck risks.

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.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import io.lettuce.core.ClientOptions;
import io.lettuce.core.SocketOptions;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;

@Configuration
public class lettuceSingleConfig {
// @Value("${tencent.redis.host}")
// private String redisHost;
//
// @Value("${tencent.redis.port:6379}")
// private Integer redisPort = 6379;
//
// @Value("${tencent.redis.database:0}")
// private Integer redisDatabase = 0;
//
// @Value("${tencent.redis.password:}")
// private String redisPassword;

@Value("${tencent.redis.connect.timeout:2000}")
private Integer redisConnectTimeout = 2000;

@Value("${tencent.redis.command.timeout:2000}")
private Integer redisCommandTimeout = 2000;
/**
* TCP_KEEPALIVE configuration parameters.
*/
@Value("${tencent.redis.tcp.keepalive.time.idle:30}")
private Integer redisTcpKeepaliveTimeIdle = 30;
@Value("${tencent.redis.tcp.keepalive.time.interval:10}")
private Integer redisTcpKeepaliveTimeInterval = 10;
@Value("${tencent.redis.tcp.keepalive.count:3}")
private Integer redisTcpKeepaliveCount = 3;

/**
* TCP_USER_TIMEOUT resolves the Lettuce long timeout issue.
*/
@Value("${tencent.redis.tcp.user.timeout:30}")
private Integer redisTcpUserTimeout = 30;

/**
* Pool-related parameters.
*/
@Value("${tencent.redis.pool.max-wait:1000}")
private Integer RedisPoolMaxwait = 1000;
@Value("${tencent.redis.pool.max-active:2000}")
private Integer RedisPoolMaxTotal = 2000;
@Value("${tencent.redis.pool.max-idle:1000}")
private Integer RedisPoolMaxIdle = 1000;
@Value("${tencent.redis.pool.min-idle:500}")
private Integer RedisPoolMinIdle = 500;

/**
* redisConnectionFactory and related parameters (Host, Port, Database, and Password) can be configured either here or in application.properties (choose one method).
*/
// @Bean
// public LettuceConnectionFactory redisConnectionFactory(LettuceClientConfiguration clientConfiguration) {
//
// RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration();
// standaloneConfiguration.setHostName(redisHost);
// standaloneConfiguration.setPort(redisPort);
// standaloneConfiguration.setDatabase(redisDatabase);
// standaloneConfiguration.setPassword(redisPassword);
//
// LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(standaloneConfiguration, clientConfiguration);
// connectionFactory.setDatabase(redisDatabase);
// return connectionFactory;
// }

@Bean
public LettuceClientConfiguration clientConfiguration() {


SocketOptions socketOptions = SocketOptions.builder()
.keepAlive(SocketOptions.KeepAliveOptions.builder()
// How long a connection remains idle before keepalive is started.
.idle(Duration.ofSeconds(redisTcpKeepaliveTimeIdle))
// Time interval between two keepalives.
.interval(Duration.ofSeconds(redisTcpKeepaliveTimeInterval))
// Number of keepalives before the connection is disabled.
.count(redisTcpKeepaliveCount)
// Whether to enable keepalive connection.
.enable()
.build())
.tcpUserTimeout(SocketOptions.TcpUserTimeoutOptions.builder()
// Resolve the long timeout issue caused by server rst.
.tcpUserTimeout(Duration.ofSeconds(redisTcpUserTimeout))
.enable()
.build())
// Set TCP connection timeout.
.connectTimeout(Duration.ofMillis(redisConnectTimeout))
.build();

ClientOptions clientOptions = ClientOptions.builder()
.autoReconnect(true)
.pingBeforeActivateConnection(true)
.cancelCommandsOnReconnectFailure(false)
.disconnectedBehavior(ClientOptions.DisconnectedBehavior.ACCEPT_COMMANDS)
.socketOptions(socketOptions)
.build();

// Create connection pool configuration and disable LIFO.
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setLifo(false); // Disable LIFO and enable FIFO.
poolConfig.setMaxTotal(RedisPoolMaxTotal); // Set maximum number of connections (optional).
poolConfig.setMaxIdle(RedisPoolMaxIdle); // Set maximum number of idle connections (optional).
poolConfig.setMinIdle(RedisPoolMinIdle); // Set minimum number of idle connections (optional).
poolConfig.setMaxWait(Duration.ofMillis(RedisPoolMaxwait));

return LettucePoolingClientConfiguration.builder()
.poolConfig(poolConfig)
.commandTimeout(Duration.ofMillis(redisCommandTimeout))
.clientOptions(clientOptions)
.build();
}
}

Ajuda e Suporte

Esta página foi útil?

comentários