redis在spring boot中的集成(单容器和分布式连接配置)

redis在spring boot中的集成方式如下
1、配置依赖包
compile( "com.corundumstudio.socketio:netty-socketio:1.7.12" )
2、配置 application.yml
jedis:
 isCluster: false # 默认选择集群方式
 pool:
     cluster: #集群模式
     url: 172.18.24.128:26379,172.18.24.129:26379,172.18.24.130:26379 # redis集群环境 ip+端口 依次以逗号分隔
     masterName: mymaster
     single: # 单容器模式
     redisHost: 172.18.8.29
     redisPort: 6379
3、redis连接
/**
* 从连接池获取redis连接 @return the jedis
* * 从哨兵获取redis连接 @return the jedis from sentinel
*
* @return the jedis
*/
public static synchronized Jedis getJedis() {
if ( jedisUtils .isCluster ) {
  return getJedisByCluster ();
 } else {
 return getJedisBySingle ();
 }
}

/**
* swarm 集群模式
* @return
*/
public static synchronized Jedis  getJedisByCluster () {
if ( jedisSentinelPool == null ) {
JedisPoolConfig jedisPoolConfig = JedisUtils. createPoolConfig ( jedisUtils . maxIdle , jedisUtils . maxTotal , jedisUtils . checkingIntervalSecs , jedisUtils . evictableIdleTimeSecs );
Set<String> sentinels = new HashSet<>(Arrays. asList (StringUtils. split ( jedisUtils . url , "," )));
jedisSentinelPool = new JedisSentinelPool( jedisUtils . masterName , sentinels, jedisPoolConfig, 5000 );
HostAndPort currentHostMaster = jedisSentinelPool .getCurrentHostMaster();
logger .info( "Get current host message" + currentHostMaster.getHost() + "Get current port message" + currentHostMaster.getPort());
}
return jedisSentinelPool .getResource();
}

/**
* 单容器模式
* @return
*/
public static synchronized Jedis getJedisBySingle() {
if ( jedisPool == null ) {
JedisPoolConfig poolConfig = JedisUtils. createPoolConfig ( 300 , 1000 , 300 , 300 );
jedisPool = new JedisPool(poolConfig, jedisUtils . redisHost , jedisUtils . redisPort );
}
return jedisPool .getResource();
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值