Spring-boot構成JedisShardInfo
1675 ワード
構成クラス:
Propertiesの情報は次のとおりです.
Environmentオブジェクトからproperty情報を取得できます
@Configuration
public class RedisConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix = "spring.redis.pool")
public JedisPoolConfig getJedisPoolConfig() {
return new JedisPoolConfig();
}
@Bean
public ShardedJedisPool getJedisPool() {
try {
List<JedisShardInfo> shardList = new ArrayList<>();
int index = 1;
while(true){
// host
String host = env.getProperty("spring.redis.shard."+index+".host");
if(StringUtils.isEmpty(host)){
break;
}
// port
String port = env.getProperty("spring.redis.shard."+index+".port");
JedisShardInfo info = new JedisShardInfo(host, Integer.valueOf(port), 0, "");
// password
String password = env.getProperty("spring.redis.shard."+index+".password");
if(!StringUtils.isEmpty(password)){
info.setPassword(password);
}
shardList.add(info);
index++;
}
if(shardList.size() == 0){
// redis
throw new IOException();
}
return new ShardedJedisPool(getJedisPoolConfig(), shardList);
} catch (Exception e) {
throw new RuntimeException(" !");
}
}
}
Propertiesの情報は次のとおりです.
# Redis config
spring.redis.shard.1.host = 127.0.0.1
spring.redis.shard.1.password =
spring.redis.shard.1.port = 6379
spring.redis.pool.maxIdle = 20
spring.redis.pool.maxTotal = 20
spring.redis.pool.numTestsPerEvictionRun = 3
spring.redis.pool.testOnBorrow = true
spring.redis.pool.blockWhenExhausted = false
spring.redis.pool.testOnReturn = false
Environmentオブジェクトからproperty情報を取得できます