1.springBoot集成redisson(單機,集羣,哨兵)
redisson版本使用3.8.2
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.8.2</version>
</dependency>
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
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
/*
@author Abbotbr/> * @des
* @date 2018/10/18 10:42
**/
@ConfigurationProperties(prefix = "spring.redis", ignoreUnknownFields = false)br/>@Data
@ToString
public class RedisProperties {
private int database;
/*
等待節點回覆命令的時間。該時間從命令發送成功時開始計時
*/
private int timeout;
private String password;
private String mode;
/*
池配置
*/
private RedisPoolProperties pool;
/*
單機信息配置
*/
private RedisSingleProperties single;
/*
集羣 信息配置
*/
private RedisClusterProperties cluster;
/*
哨兵配置
*/
private RedisSentinelProperties sentinel;
}
池配置RedisPoolProperties
import lombok.Data;
import lombok.ToString;
/*
@author Abbotbr/> * @des redis 池配置
* @date 2018/10/18 10:43br/> **/
@Data
@ToString
public class RedisPoolProperties {
private int maxIdle;
private int minIdle;
private int maxActive;
private int maxWait;
private int connTimeout;
private int soTimeout;
/*
池大小
*/
private int size;
}
RedisSingleProperties
@Databr/>@ToString
public class RedisSingleProperties {
private String address;
}
集羣配置RedisClusterProperties
@Databr/>@ToString
public class RedisClusterProperties {
/*
集羣狀態掃描間隔時間,單位是毫秒
*/
private int scanInterval;
/*
集羣節點
*/
private String nodes;
/*
默認值: SLAVE(只在從服務節點裏讀取)設置讀取操作選擇節點的模式。 可用值爲: SLAVE - 只在從服務節點裏讀取。
MASTER - 只在主服務節點裏讀取。 MASTER_SLAVE - 在主從服務節點裏都可以讀取
/
private String readMode;
/
(從節點連接池大小) 默認值:64
/
private int slaveConnectionPoolSize;
/
主節點連接池大小)默認值:64
/
private int masterConnectionPoolSize;
/*
(命令失敗重試次數) 默認值:3
*/
private int retryAttempts;
/*
命令重試發送時間間隔,單位:毫秒 默認值:1500
*/
private int retryInterval;
/*
執行失敗最大次數默認值:3
*/
private int failedAttempts;
}
哨兵配置 RedisSentinelProperties
@Databr/>@ToString
public class RedisSentinelProperties {
/*
哨兵master 名稱
*/
private String master;
/*
哨兵節點
*/
private String nodes;
/*
哨兵配置
*/
private boolean masterOnlyWrite;
/*
*/
private int failMax;
}
4.CacheConfiguration
@Configurationbr/>@EnableConfigurationProperties(RedisProperties.class)
public class CacheConfiguration {
@Autowired
RedisProperties redisProperties;
/*
單機模式 redisson 客戶端
*/
/*
集羣模式的 redisson 客戶端br/> *
* @return
*/br/> @Bean
@ConditionalOnProperty(name = "spring.redis.mode", havingValue = "cluster")
RedissonClient redissonCluster() {
System.out.println("cluster redisProperties:" + redisProperties.getCluster());
Config config = new Config();
String[] nodes = redisProperties.getCluster().getNodes().split(",");
List<String> newNodes = new ArrayList(nodes.length);
Arrays.stream(nodes).forEach((index) -> newNodes.add(
index.startsWith("redis://") ? index : "redis://" + index));
ClusterServersConfig serverConfig = config.useClusterServers()
.addNodeAddress(newNodes.toArray(new String[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());
}
return Redisson.create(config);
}
/*
哨兵模式 redisson 客戶端br/> * @return
*/
SentinelServersConfig serverConfig = config.useSentinelServers()
.addSentinelAddress(newNodes.toArray(new String[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());
}
return Redisson.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")br/> public @ResponseBody
ServerResponse<RLock> lock(@RequestBody ServerRequest<LockReqBody> req) {
return callR(redisson -> {
RLock lock = redisson.getLock(req.getReqBody().getLockKey());
lock.lock(req.getReqBody().getTimeout(), req.getReqBody().getUnit());
return lock;
});
}
//省略部分代碼
private <R> ServerResponse callR(Function<RedissonClient, R> function) {
ServerResponse dv = RespHelper.serverResponse(RespCodeService.ERROR, "");
try {
long startTime = 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");
}
return dv;
}
歡迎工作一到五年的Java工程師朋友們加入Java架構開發: 855835163
羣內提供免費的Java架構學習資料(裏面有高可用、高併發、高性能及分佈式、Jvm性能調優、Spring源碼,MyBatis,Netty,Redis,Kafka,Mysql,Zookeeper,Tomcat,Docker,Dubbo,Nginx等多個知識點的架構資料)合理利用自己每一分每一秒的時間來學習提升自己,不要再用"沒有時間“來掩飾自己思想上的懶惰!趁年輕,使勁拼,給未來的自己一個交代!