Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save doppiomacchiatto/8629f705784b38d67188e88deac147ad to your computer and use it in GitHub Desktop.
Save doppiomacchiatto/8629f705784b38d67188e88deac147ad to your computer and use it in GitHub Desktop.
Lettuce Redis Connection pooling through Spring RedisTemplate
import org.apache.commons.pool.impl.GenericObjectPool.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.lettuce.DefaultLettucePool;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class LettuceRedisClientConnectionPooling {
@Value("${redis.cache.hostname}")
private String redisHost;
@Value("${redis.cache.port}")
private Integer redisPort;
@Value("${redis.cache.thread.maxActive}")
private Integer MAXACTIVE;
@Value("${redis.cache.thread.maxIdle}")
private Integer MAXIDLE;
@Bean
public StringRedisTemplate getStringRedisTemplate() {
StringRedisTemplate redisTemplate = new StringRedisTemplate(getLettuceConnectionFactory());
return redisTemplate;
}
private LettuceConnectionFactory getLettuceConnectionFactory() {
DefaultLettucePool lettucePool = new DefaultLettucePool(redisHost,redisPort,getPoolConfig());
lettucePool.afterPropertiesSet();
LettuceConnectionFactory lcf = new LettuceConnectionFactory(lettucePool);
lcf.afterPropertiesSet();
lcf.setShareNativeConnection(false);
return lcf;
}
private Config getPoolConfig(){
Config poolConfig = new Config();
poolConfig.maxActive = 16;
if(MAXACTIVE!=null && MAXACTIVE > 0){
poolConfig.maxActive = MAXACTIVE;
}
poolConfig.maxIdle = 16;
if(MAXIDLE!=null && MAXIDLE > 0){
poolConfig.maxIdle = MAXIDLE;
}
poolConfig.minIdle = 0;
return poolConfig;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment