Spring cloud

SpringBoot集成redisson(单机,集群,哨兵)

2018-10-24  本文已影响100人  Java大生

1.springBoot集成redisson(单机,集群,哨兵)

redisson版本使用3.8.2

org.redisson

redisson

3.8.2

2.配置文件

application.properties

spring.redis.database=0

spring.redis.password=

spring.redis.timeout=3000

#sentinel/cluster/single

spring.redis.mode=single

#连接池配置

spring.redis.pool.max-idle=16

spring.redis.pool.min-idle=8

spring.redis.pool.max-active=8

spring.redis.pool.max-wait=3000

spring.redis.pool.conn-timeout=3000

spring.redis.pool.so-timeout=3000

spring.redis.pool.size=10

#单机配置

spring.redis.single.address=192.168.60.23:6379

#集群配置

spring.redis.cluster.scan-interval=1000

spring.redis.cluster.nodes=

spring.redis.cluster.read-mode=SLAVE

spring.redis.cluster.retry-attempts=3

spring.redis.cluster.failed-attempts=3

spring.redis.cluster.slave-connection-pool-size=64

spring.redis.cluster.master-connection-pool-size=64

spring.redis.cluster.retry-interval=1500

#哨兵配置

spring.redis.sentinel.master=business-master

spring.redis.sentinel.nodes=

spring.redis.sentinel.master-onlyWrite=true

spring.redis.sentinel.fail-max=3

3.配置文件读取

RedisProperties

importlombok.Data;

importlombok.ToString;

importorg.springframework.boot.context.properties.ConfigurationProperties;

/**

* @author Abbot

* @des

* @date 2018/10/18 10:42

**/

@ConfigurationProperties(prefix ="spring.redis", ignoreUnknownFields =false)

@Data

@ToString

publicclassRedisProperties{

privateintdatabase;

/**

* 等待节点回复命令的时间。该时间从命令发送成功时开始计时

*/

privateinttimeout;

privateString password;

privateString mode;

/**

* 池配置

*/

privateRedisPoolProperties pool;

/**

* 单机信息配置

*/

privateRedisSingleProperties single;

/**

* 集群 信息配置

*/

privateRedisClusterProperties cluster;

/**

* 哨兵配置

*/

privateRedisSentinelProperties sentinel;

}

池配置RedisPoolProperties

importlombok.Data;

importlombok.ToString;

/**

*@authorAbbot

*@desredis 池配置

*@date2018/10/18 10:43

**/

@Data

@ToString

publicclassRedisPoolProperties{

privateintmaxIdle;

privateintminIdle;

privateintmaxActive;

privateintmaxWait;

privateintconnTimeout;

privateintsoTimeout;

/**

* 池大小

*/

privateintsize;

}

RedisSingleProperties

@Data

@ToString

publicclassRedisSingleProperties{

privateString address;

}

集群配置RedisClusterProperties

@Data

@ToString

publicclassRedisClusterProperties{

/**

* 集群状态扫描间隔时间,单位是毫秒

*/

privateintscanInterval;

/**

* 集群节点

*/

privateString nodes;

/**

* 默认值: SLAVE(只在从服务节点里读取)设置读取操作选择节点的模式。 可用值为: SLAVE - 只在从服务节点里读取。

* MASTER - 只在主服务节点里读取。 MASTER_SLAVE - 在主从服务节点里都可以读取

*/

privateString readMode;

/**

* (从节点连接池大小) 默认值:64

*/

privateintslaveConnectionPoolSize;

/**

* 主节点连接池大小)默认值:64

*/

privateintmasterConnectionPoolSize;

/**

* (命令失败重试次数) 默认值:3

*/

privateintretryAttempts;

/**

*命令重试发送时间间隔,单位:毫秒 默认值:1500

*/

privateintretryInterval;

/**

* 执行失败最大次数默认值:3

*/

privateintfailedAttempts;

}

哨兵配置 RedisSentinelProperties

@Data

@ToString

publicclassRedisSentinelProperties{

/**

* 哨兵master 名称

*/

privateString master;

/**

* 哨兵节点

*/

privateString nodes;

/**

* 哨兵配置

*/

privateboolean masterOnlyWrite;

/**

*

*/

privateintfailMax;

}

4.CacheConfiguration

@Configuration

@EnableConfigurationProperties(RedisProperties.class)

publicclassCacheConfiguration{

@Autowired

RedisProperties redisProperties;

@Configuration

@ConditionalOnClass({Redisson.class})

@ConditionalOnExpression("'${spring.redis.mode}'=='single' or '${spring.redis.mode}'=='cluster' or '${spring.redis.mode}'=='sentinel'")

protectedclassRedissonSingleClientConfiguration{

/**

* 单机模式 redisson 客户端

*/

@Bean

@ConditionalOnProperty(name ="spring.redis.mode", havingValue ="single")

RedissonClient redissonSingle() {

Config config =newConfig();

Stringnode = redisProperties.getSingle().getAddress();

node = node.startsWith("redis://") ? node :"redis://"+ node;

SingleServerConfig serverConfig = config.useSingleServer()

.setAddress(node)

.setTimeout(redisProperties.getPool().getConnTimeout())

.setConnectionPoolSize(redisProperties.getPool().getSize())

.setConnectionMinimumIdleSize(redisProperties.getPool().getMinIdle());

if(StringUtils.isNotBlank(redisProperties.getPassword())) {

serverConfig.setPassword(redisProperties.getPassword());

}

returnRedisson.create(config);

}

/**

* 集群模式的 redisson 客户端

*

* @return

*/

@Bean

@ConditionalOnProperty(name ="spring.redis.mode", havingValue ="cluster")

RedissonClient redissonCluster() {

System.out.println("cluster redisProperties:"+ redisProperties.getCluster());

Config config =newConfig();

String[] nodes = redisProperties.getCluster().getNodes().split(",");

List newNodes =newArrayList(nodes.length);

Arrays.stream(nodes).forEach((index) -> newNodes.add(

index.startsWith("redis://") ? index :"redis://"+ index));

ClusterServersConfig serverConfig = config.useClusterServers()

.addNodeAddress(newNodes.toArray(newString[0]))

.setScanInterval(

redisProperties.getCluster().getScanInterval())

.setIdleConnectionTimeout(

redisProperties.getPool().getSoTimeout())

.setConnectTimeout(

redisProperties.getPool().getConnTimeout())

.setFailedAttempts(

redisProperties.getCluster().getFailedAttempts())

.setRetryAttempts(

redisProperties.getCluster().getRetryAttempts())

.setRetryInterval(

redisProperties.getCluster().getRetryInterval())

.setMasterConnectionPoolSize(redisProperties.getCluster()

.getMasterConnectionPoolSize())

.setSlaveConnectionPoolSize(redisProperties.getCluster()

.getSlaveConnectionPoolSize())

.setTimeout(redisProperties.getTimeout());

if(StringUtils.isNotBlank(redisProperties.getPassword())) {

serverConfig.setPassword(redisProperties.getPassword());

}

returnRedisson.create(config);

}

/**

* 哨兵模式 redisson 客户端

* @return

*/

@Bean

@ConditionalOnProperty(name ="spring.redis.mode", havingValue ="sentinel")

RedissonClient redissonSentinel() {

System.out.println("sentinel redisProperties:"+ redisProperties.getSentinel());

Config config =newConfig();

String[] nodes = redisProperties.getSentinel().getNodes().split(",");

List newNodes =newArrayList(nodes.length);

Arrays.stream(nodes).forEach((index) -> newNodes.add(

index.startsWith("redis://") ? index :"redis://"+ index));

SentinelServersConfig serverConfig = config.useSentinelServers()

.addSentinelAddress(newNodes.toArray(newString[0]))

.setMasterName(redisProperties.getSentinel().getMaster())

.setReadMode(ReadMode.SLAVE)

.setFailedAttempts(redisProperties.getSentinel().getFailMax())

.setTimeout(redisProperties.getTimeout())

.setMasterConnectionPoolSize(redisProperties.getPool().getSize())

.setSlaveConnectionPoolSize(redisProperties.getPool().getSize());

if(StringUtils.isNotBlank(redisProperties.getPassword())) {

serverConfig.setPassword(redisProperties.getPassword());

}

returnRedisson.create(config);

}

}

}

5.使用时候直接注入RedissClient客户端就可以使用

如下这样写的目的是为了统一给其它服务提供接口

@Autowired

RedissonClient redisson;

@RequestMapping(value="lock", method = RequestMethod.POST, consumes ="application/json;charset=UTF-8", produces ="application/json;charset=UTF-8")

public@ResponseBody

ServerResponselock(@RequestBody ServerRequest<LockReqBody> req)

{

returncallR(redisson -> {

RLocklock= redisson.getLock(req.getReqBody().getLockKey());

lock.lock(req.getReqBody().getTimeout(), req.getReqBody().getUnit());

returnlock;

});

}

//省略部分代码

privateServerResponsecallR(Function<RedissonClient, R> function){

ServerResponse dv = RespHelper.serverResponse(RespCodeService.ERROR,"");

try{

longstartTime = System.currentTimeMillis();

dv = RespHelper.serverResponse(RespCodeService.SUCCESS, function.apply(redisson));

logger.info("CALLR METHOD USE TIME:{}", System.currentTimeMillis() - startTime);

}catch(Throwable e) {

System.out.println("callR error");

}

returndv;

}

欢迎工作一到五年的Java工程师朋友们加入Java架构开发: 855835163

群内提供免费的Java架构学习资料(里面有高可用、高并发、高性能及分布式、Jvm性能调优、Spring源码,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多个知识点的架构资料)合理利用自己每一分每一秒的时间来学习提升自己,不要再用"没有时间“来掩饰自己思想上的懒惰!趁年轻,使劲拼,给未来的自己一个交代!

上一篇下一篇

猜你喜欢

热点阅读