Spring-boot配置JedisShardInfo

配置类:

@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信息

 

你可能感兴趣的:(Spring-boot配置JedisShardInfo)