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

 

转载于:https://my.oschina.net/foreverZx/blog/674185

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值