2019独角兽企业重金招聘Python工程师标准>>>
配置类:
@Configuration
public class RedisConfig {@Autowiredprivate Environment env;@Bean@ConfigurationProperties(prefix = "spring.redis.pool")public JedisPoolConfig getJedisPoolConfig() {return new JedisPoolConfig();}@Beanpublic ShardedJedisPool getJedisPool() {try {List<JedisShardInfo> shardList = new ArrayList<>();int index = 1;while(true){//读取hostString host = env.getProperty("spring.redis.shard."+index+".host");if(StringUtils.isEmpty(host)){break;}//读取portString port = env.getProperty("spring.redis.shard."+index+".port");JedisShardInfo info = new JedisShardInfo(host, Integer.valueOf(port), 0, "");//读取passwordString password = env.getProperty("spring.redis.shard."+index+".password");if(!StringUtils.isEmpty(password)){info.setPassword(password);}shardList.add(info);index++;}if(shardList.size() == 0){//无法加载redisthrow 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 = 6379spring.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信息