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();
}