Spring Boot 整合 Redis 單機、集群、哨兵模式實踐
作者:一安
哨兵模式主要為解決Redis的高可用性問題而設計。它由多個哨兵節點組成,這些哨兵節點會持續監控Redis主節點和從節點的運行狀態。
前言
Redis
作為一款高性能的內存數據庫,憑借其出色的讀寫速度、豐富的數據結構以及靈活的部署模式,成為了眾多開發者緩存、消息隊列等場景的首選方案。
本文將探討如何通過Spring Boot
實現Redis
單機、集群、哨兵模式的整合與應用。
部署模式
- 單機模式:這是
Redis
最基礎的部署方式,所有數據存儲在單個Redis
實例中。其優點在于配置簡單、部署便捷,適合小型項目或開發測試環境。但單機模式存在明顯的局限性,如數據存儲量受限于單機內存,且不具備高可用性,一旦服務器宕機,服務將無法正常使用。 - 集群模式:集群模式通過將數據分散存儲在多個節點上,解決了單機模式下數據存儲量和性能瓶頸的問題。它支持水平擴展,能夠輕松應對大規模數據和高并發請求。在集群模式中,每個節點負責部分數據的存儲和讀寫操作,節點之間通過
Gossip
協議進行通信和數據同步。這種模式適用于對性能和數據存儲量要求較高的大型應用場景。
- 哨兵模式:哨兵模式主要為解決
Redis
的高可用性問題而設計。它由多個哨兵節點組成,這些哨兵節點會持續監控Redis
主節點和從節點的運行狀態。當主節點出現故障時,哨兵節點會自動進行故障檢測和故障轉移,將從節點提升為主節點,確保服務的連續性。哨兵模式在保證數據安全性和服務穩定性方面表現出色,常用于對服務可用性要求極高的生產環境。
實現
配置文件
spring:
redis:
# 可選模式:single(單機)、cluster(集群)、sentinel(哨兵)
mode: single
password: 123456
# 單機配置
host: 127.0.0.1
port: 6379
database: 0
# 集群配置
cluster:
nodes: 127.0.0.1:7001,127.0.0.1:7002,127.0.0.1:7003
max-redirects: 3
# 哨兵配置
sentinel:
master: mymaster
nodes: 127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381
# 連接池配置
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 8
min-idle: 0
配置類
根據配置文件中的模式,動態注入相應的RedisConnectionFactory
。
@Configuration
public class RedisConfig {
@Value("${redis.mode:single}")
private String redisMode;
// 單機配置
@Value("${spring.redis.host:localhost}")
private String host;
@Value("${spring.redis.port:6379}")
private int port;
@Value("${spring.redis.password:}")
private String password;
@Value("${spring.redis.database:}")
private int database;
// 集群配置
@Value("${spring.redis.cluster.nodes:}")
private String clusterNodes;
@Value("${spring.redis.cluster.max-redirects:3}")
private Integer maxRedirects;
// 哨兵配置
@Value("${spring.redis.sentinel.master:}")
private String sentinelMaster;
@Value("${spring.redis.sentinel.nodes:}")
private String sentinelNodes;
// 連接池配置
@Value("${spring.redis.jedis.pool.max-active:8}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-wait:-1}")
private int maxWait;
@Value("${spring.redis.jedis.pool.max-idle:8}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle:0}")
private int minIdle;
@Bean
public JedisPoolConfig jedisPoolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWait(Duration.ofMillis(maxWait));
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
return poolConfig;
}
@Bean
@Primary
public RedisConnectionFactory redisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
switch (redisMode) {
case"cluster":
return createClusterConnectionFactory(jedisPoolConfig);
case"sentinel":
return createSentinelConnectionFactory(jedisPoolConfig);
case"single":
default:
return createSingleConnectionFactory(jedisPoolConfig);
}
}
private RedisConnectionFactory createSingleConnectionFactory(JedisPoolConfig jedisPoolConfig) {
JedisClientConfiguration clientConfig = JedisClientConfiguration.builder()
.usePooling()
.poolConfig(jedisPoolConfig)
.build();
RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration();
standaloneConfig.setHostName(host);
standaloneConfig.setPort(port);
if (StringUtils.hasText(password)) {
standaloneConfig.setPassword(RedisPassword.of(password));
}
standaloneConfig.setDatabase(database);
return new JedisConnectionFactory(standaloneConfig, clientConfig);
}
private RedisConnectionFactory createClusterConnectionFactory(JedisPoolConfig jedisPoolConfig) {
List<String> nodes = Arrays.asList(clusterNodes.split(","));
List<RedisNode> redisNodes = nodes.stream()
.map(node -> {
String[] parts = node.split(":");
return new RedisNode(parts[0], Integer.parseInt(parts[1]));
})
.collect(Collectors.toList());
RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration();
clusterConfig.setClusterNodes(redisNodes);
clusterConfig.setMaxRedirects(maxRedirects);
if (!password.isEmpty()) {
clusterConfig.setPassword(password);
}
return new JedisConnectionFactory(clusterConfig, jedisPoolConfig);
}
private RedisConnectionFactory createSentinelConnectionFactory(JedisPoolConfig jedisPoolConfig) {
List<String> nodes = Arrays.asList(sentinelNodes.split(","));
RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration();
sentinelConfig.master(sentinelMaster);
for (String node : nodes) {
String[] parts = node.split(":");
sentinelConfig.sentinel(parts[0], Integer.parseInt(parts[1]));
}
if (!password.isEmpty()) {
sentinelConfig.setPassword(password);
}
sentinelConfig.setDatabase(database);
return new JedisConnectionFactory(sentinelConfig, jedisPoolConfig);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType(Object.class)
.build();
objectMapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template
}
/**
* 對redis字符串類型數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
return redisTemplate.opsForValue();
}
/**
* 對hash類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}
/**
* 對鏈表類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}
/**
* 對無序集合類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}
/**
* 對有序集合類型的數據操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}
業務操作封裝
封裝常用的Redis
操作方法,涵蓋字符串、哈希、列表、集合等數據結構的增刪改查。
@Service
@RequiredArgsConstructor(onConstructor_ = {@Lazy, @Autowired})
public class RedisServiceImpl implements RedisService {
private static final Long SUCCESS = 1L;
private final RedisTemplate<String, String> redisTemplate;
private final StringRedisTemplate stringRedisTemplate;
private final ValueOperations<String, String> valueOperations;
private final HashOperations<String, String, Object> hashOperations;
private final ListOperations<String, Object> listOperations;
private final SetOperations<String, Object> setOperations;
private final ZSetOperations<String, Object> zSetOperations;
// static {
// DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
// redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/xxxx.lua")));
// redisScript.setResultType(Long.class);
// }
/** -------------------分布式鎖相關操作--------------------- */
/**
* 獲取鎖
*
* @param lockKey
* @param value
* @param expireTime:單位-秒
* @return
*/
@Override
public boolean getLock(String lockKey, Object value, int expireTime) {
try {
String script = "if redis.call('set',KEYS[1],ARGV[1],'NX') then " +
"if redis.call('get',KEYS[1])==ARGV[1] then " +
"return redis.call('expire',KEYS[1],ARGV[2]) " +
"else " +
"return 0 end " +
"else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<Long>(script, Long.class);
Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value + "", expireTime + "");
if (SUCCESS.equals(result)) returntrue;
} catch (Exception e) {
e.printStackTrace();
}
returnfalse;
}
/**
* 釋放鎖
*
* @param lockKey
* @param value
* @return
*/
@Override
public boolean releaseLock(String lockKey, String value) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
Object result = stringRedisTemplate.execute(redisScript, Collections.singletonList(lockKey), value);
if (SUCCESS.equals(result)) {
returntrue;
}
returnfalse;
}
/** -------------------key相關操作--------------------- */
/**
* 刪除key
*
* @param key
*/
@Override
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 批量刪除key
*
* @param keys
*/
@Override
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
/**
* 序列化key
*
* @param key
* @return
*/
@Override
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
/**
* 是否存在key
*
* @param key
* @return
*/
@Override
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 設置過期時間 TimeUnit
* <p>
* TimeUnit
*
* @param key
* @param timeout
* @param unit TimeUnit.HOURS TimeUnit.DAYS
* @return
*/
@Override
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 設置過期時間
*
* @param key
* @param date
* @return
*/
@Override
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
/**
* 將當前數據庫的 key 移動到給定的數據庫 db 當中
*
* @param key
* @param dbIndex
* @return
*/
@Override
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
/**
* 移除 key 的過期時間,key 將持久保持
*
* @param key
* @return
*/
@Override
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的過期時間
*
* @param key
* @param unit
* @return
*/
@Override
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的剩余的過期時間
*
* @param key
* @return
*/
@Override
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
/**
* 從當前數據庫中隨機返回一個 key
*
* @return
*/
@Override
public String randomKey() {
return redisTemplate.randomKey();
}
/**
* 修改 key 的名稱
*
* @param oldKey
* @param newKey
*/
@Override
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* 僅當 newkey 不存在時,將 oldKey 改名為 newkey
*
* @param oldKey
* @param newKey
* @return
*/
@Override
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所儲存的值的類型
*
* @param key
* @return
*/
@Override
public DataType type(String key) {
return redisTemplate.type(key);
}
/** -------------------string相關操作--------------------- */
/**
* 設置指定 key 的值
*
* @param key
* @param value
*/
@Override
public void set(String key, String value) {
valueOperations.set(key, value);
}
/**
* 獲取指定 key 的值
*
* @param key
* @return
*/
@Override
public Object get(String key) {
return valueOperations.get(key);
}
/**
* 返回 key 中字符串值的子字符
*
* @param key
* @param start
* @param end
* @return
*/
@Override
public Object getRange(String key, long start, long end) {
return valueOperations.get(key, start, end);
}
/**
* 將給定 key 的值設為 value ,并返回 key 的舊值(old value)
*
* @param key
* @param value
* @return
*/
@Override
public Object getAndSet(String key, String value) {
return valueOperations.getAndSet(key, value);
}
/**
* 對 key 所儲存的字符串值,獲取指定偏移量上的位(bit)
*
* @param key
* @param offset
* @return
*/
@Override
public Boolean getBit(String key, long offset) {
return valueOperations.getBit(key, offset);
}
/**
* 批量獲取
*
* @param keys
* @return
*/
@Override
public List<String> multiGet(Collection<String> keys) {
return valueOperations.multiGet(keys);
}
/**
* 設置ASCII碼, 字符串'a'的ASCII碼是97, 轉為二進制是'01100001', 此方法是將二進制第offset位值變為value
*
* @param key
* @param offset 位置
* @param value 值,true為1, false為0
* @return
*/
@Override
public boolean setBit(String key, long offset, boolean value) {
return valueOperations.setBit(key, offset, value);
}
/**
* 將值 value 關聯到 key ,并將 key 的過期時間設為 timeout
*
* @param key
* @param value
* @param timeout 過期時間
* @param unit 時間單位, 天:TimeUnit.DAYS 小時:TimeUnit.HOURS 分鐘:TimeUnit.MINUTES
* 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
*/
@Override
public void setEx(String key, String value, long timeout, TimeUnit unit) {
valueOperations.set(key, value, timeout, unit);
}
/**
* 只有在 key 不存在時設置 key 的值
*
* @param key
* @param value
* @return 之前已經存在返回false, 不存在返回true
*/
@Override
public boolean setIfAbsent(String key, String value) {
return valueOperations.setIfAbsent(key, value);
}
/**
* 用 value 參數覆寫給定 key 所儲存的字符串值,從偏移量 offset 開始
*
* @param key
* @param value
* @param offset 從指定位置開始覆寫
*/
@Override
public void setRange(String key, String value, long offset) {
valueOperations.set(key, value, offset);
}
/**
* 獲取字符串的長度
*
* @param key
* @return
*/
@Override
public Long size(String key) {
return valueOperations.size(key);
}
/**
* 批量添加
*
* @param maps
*/
@Override
public void multiSet(Map<String, String> maps) {
valueOperations.multiSet(maps);
}
/**
* 同時設置一個或多個 key-value 對,當且僅當所有給定 key 都不存在
*
* @param maps
* @return 之前已經存在返回false, 不存在返回true
*/
@Override
public boolean multiSetIfAbsent(Map<String, String> maps) {
return valueOperations.multiSetIfAbsent(maps);
}
/**
* 增加(自增長), 負數則為自減
*
* @param key
* @param increment
* @return
*/
@Override
public Long incrBy(String key, long increment) {
return valueOperations.increment(key, increment);
}
/**
* @param key
* @param increment
* @return
*/
@Override
public Double incrByFloat(String key, double increment) {
return valueOperations.increment(key, increment);
}
/**
* 追加到末尾
*
* @param key
* @param value
* @return
*/
@Override
public Integer append(String key, String value) {
return valueOperations.append(key, value);
}
/** -------------------hash相關操作------------------------- */
/**
* 獲取存儲在哈希表中指定字段的值
*
* @param key
* @param field
* @return
*/
@Override
public Object hGet(String key, String field) {
return hashOperations.get(key, field);
}
/**
* 獲取所有給定字段的值
*
* @param key
* @return
*/
@Override
public Map<String, Object> hGetAll(String key) {
return hashOperations.entries(key);
}
/**
* 獲取所有給定字段的值
*
* @param key
* @param fields
* @return
*/
@Override
public List<Object> hMultiGet(String key, List<String> fields) {
return hashOperations.multiGet(key, fields);
}
@Override
public void hPut(String key, String hashKey, String value) {
hashOperations.put(key, hashKey, value);
}
@Override
public void hPutAll(String key, Map<String, String> maps) {
hashOperations.putAll(key, maps);
}
/**
* 僅當hashKey不存在時才設置
*
* @param key
* @param hashKey
* @param value
* @return
*/
@Override
public Boolean hPutIfAbsent(String key, String hashKey, String value) {
return hashOperations.putIfAbsent(key, hashKey, value);
}
/**
* 刪除一個或多個哈希表字段
*
* @param key
* @param fields
* @return
*/
@Override
public Long hDelete(String key, Object... fields) {
return hashOperations.delete(key, fields);
}
/**
* 查看哈希表 key 中,指定的字段是否存在
*
* @param key
* @param field
* @return
*/
@Override
public boolean hExists(String key, String field) {
return hashOperations.hasKey(key, field);
}
/**
* 為哈希表 key 中的指定字段的整數值加上增量 increment
*
* @param key
* @param field
* @param increment
* @return
*/
@Override
public Long hIncrBy(String key, String field, long increment) {
return hashOperations.increment(key, field, increment);
}
/**
* 為哈希表 key 中的指定字段的整數值加上增量 increment
*
* @param key
* @param field
* @param delta
* @return
*/
@Override
public Double hIncrByFloat(String key, String field, double delta) {
return hashOperations.increment(key, field, delta);
}
/**
* 獲取所有哈希表中的字段
*
* @param key
* @return
*/
@Override
public Set<String> hKeys(String key) {
return hashOperations.keys(key);
}
/**
* 獲取哈希表中字段的數量
*
* @param key
* @return
*/
@Override
public Long hSize(String key) {
return hashOperations.size(key);
}
/**
* 獲取哈希表中所有值
*
* @param key
* @return
*/
@Override
public List<Object> hValues(String key) {
return hashOperations.values(key);
}
/**
* 迭代哈希表中的鍵值對
*
* @param key
* @param options
* @return
*/
@Override
public Cursor<Map.Entry<String, Object>> hScan(String key, ScanOptions options) {
return hashOperations.scan(key, options);
}
/** ------------------------list相關操作---------------------------- */
/**
* 通過索引獲取列表中的元素
*
* @param key
* @param index
* @return
*/
@Override
public Object lIndex(String key, long index) {
return listOperations.index(key, index);
}
/**
* 獲取列表指定范圍內的元素
*
* @param key
* @param start 開始位置, 0是開始位置
* @param end 結束位置, -1返回所有
* @return
*/
@Override
public List<Object> lRange(String key, long start, long end) {
return listOperations.range(key, start, end);
}
/**
* 存儲在list頭部
*
* @param key
* @param value
* @return
*/
@Override
public Long lLeftPush(String key, String value) {
return listOperations.leftPush(key, value);
}
/**
* @param key
* @param value
* @return
*/
@Override
public Long lLeftPushAll(String key, String... value) {
return listOperations.leftPushAll(key, value);
}
/**
* @param key
* @param value
* @return
*/
@Override
public Long lLeftPushAll(String key, Collection<String> value) {
return listOperations.leftPushAll(key, value);
}
/**
* 當list存在的時候才加入
*
* @param key
* @param value
* @return
*/
@Override
public Long lLeftPushIfPresent(String key, String value) {
return listOperations.leftPushIfPresent(key, value);
}
/**
* 如果pivot存在,再pivot前面添加
*
* @param key
* @param pivot
* @param value
* @return
*/
@Override
public Long lLeftPush(String key, String pivot, String value) {
return listOperations.leftPush(key, pivot, value);
}
/**
* @param key
* @param value
* @return
*/
@Override
public Long lRightPush(String key, String value) {
return listOperations.rightPush(key, value);
}
/**
* @param key
* @param value
* @return
*/
@Override
public Long lRightPushAll(String key, String... value) {
return listOperations.rightPushAll(key, value);
}
/**
* @param key
* @param value
* @return
*/
@Override
public Long lRightPushAll(String key, Collection<String> value) {
return listOperations.rightPushAll(key, value);
}
/**
* 為已存在的列表添加值
*
* @param key
* @param value
* @return
*/
@Override
public Long lRightPushIfPresent(String key, String value) {
return listOperations.rightPushIfPresent(key, value);
}
/**
* 在pivot元素的右邊添加值
*
* @param key
* @param pivot
* @param value
* @return
*/
@Override
public Long lRightPush(String key, String pivot, String value) {
return listOperations.rightPush(key, pivot, value);
}
/**
* 通過索引設置列表元素的值
*
* @param key
* @param index 位置
* @param value
*/
@Override
public void lSet(String key, long index, String value) {
listOperations.set(key, index, value);
}
/**
* 移出并獲取列表的第一個元素
*
* @param key
* @return 刪除的元素
*/
@Override
public Object lLeftPop(String key) {
return listOperations.leftPop(key);
}
/**
* 移出并獲取列表的第一個元素, 如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止
*
* @param key
* @param timeout 等待時間
* @param unit 時間單位
* @return
*/
@Override
public Object lBLeftPop(String key, long timeout, TimeUnit unit) {
return listOperations.leftPop(key, timeout, unit);
}
/**
* 移除并獲取列表最后一個元素
*
* @param key
* @return 刪除的元素
*/
@Override
public Object lRightPop(String key) {
return listOperations.rightPop(key);
}
/**
* 移出并獲取列表的最后一個元素, 如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止
*
* @param key
* @param timeout 等待時間
* @param unit 時間單位
* @return
*/
@Override
public Object lBRightPop(String key, long timeout, TimeUnit unit) {
return listOperations.rightPop(key, timeout, unit);
}
/**
* 移除列表的最后一個元素,并將該元素添加到另一個列表并返回
*
* @param sourceKey
* @param destinationKey
* @return
*/
@Override
public Object lRightPopAndLeftPush(String sourceKey, String destinationKey) {
return listOperations.rightPopAndLeftPush(sourceKey,
destinationKey);
}
/**
* 從列表中彈出一個值,將彈出的元素插入到另外一個列表中并返回它; 如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止
*
* @param sourceKey
* @param destinationKey
* @param timeout
* @param unit
* @return
*/
@Override
public Object lBRightPopAndLeftPush(String sourceKey, String destinationKey,
long timeout, TimeUnit unit) {
return listOperations.rightPopAndLeftPush(sourceKey,
destinationKey, timeout, unit);
}
/**
* 刪除集合中值等于value得元素
*
* @param key
* @param index index=0, 刪除所有值等于value的元素; index>0, 從頭部開始刪除第一個值等于value的元素;
* index<0, 從尾部開始刪除第一個值等于value的元素;
* @param value
* @return
*/
@Override
public Long lRemove(String key, long index, String value) {
return listOperations.remove(key, index, value);
}
/**
* 裁剪list
*
* @param key
* @param start
* @param end
*/
@Override
public void lTrim(String key, long start, long end) {
listOperations.trim(key, start, end);
}
/**
* 獲取列表長度
*
* @param key
* @return
*/
@Override
public Long lLen(String key) {
return listOperations.size(key);
}
/** --------------------set相關操作-------------------------- */
/**
* set添加元素
*
* @param key
* @param values
* @return
*/
@Override
public Long sAdd(String key, String... values) {
return setOperations.add(key, values);
}
/**
* set移除元素
*
* @param key
* @param values
* @return
*/
@Override
public Long sRemove(String key, Object... values) {
return setOperations.remove(key, values);
}
/**
* 移除并返回集合的一個隨機元素
*
* @param key
* @return
*/
@Override
public Object sPop(String key) {
return setOperations.pop(key);
}
/**
* 將元素value從一個集合移到另一個集合
*
* @param key
* @param value
* @param destKey
* @return
*/
@Override
public Boolean sMove(String key, String value, String destKey) {
return setOperations.move(key, value, destKey);
}
/**
* 獲取集合的大小
*
* @param key
* @return
*/
@Override
public Long sSize(String key) {
return setOperations.size(key);
}
/**
* 判斷集合是否包含value
*
* @param key
* @param value
* @return
*/
@Override
public Boolean sIsMember(String key, Object value) {
return setOperations.isMember(key, value);
}
/**
* 獲取兩個集合的交集
*
* @param key
* @param otherKey
* @return
*/
@Override
public Set<Object> sIntersect(String key, String otherKey) {
return setOperations.intersect(key, otherKey);
}
/**
* 獲取key集合與多個集合的交集
*
* @param key
* @param otherKeys
* @return
*/
@Override
public Set<Object> sIntersect(String key, Collection<String> otherKeys) {
return setOperations.intersect(key, otherKeys);
}
/**
* key集合與otherKey集合的交集存儲到destKey集合中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
@Override
public Long sIntersectAndStore(String key, String otherKey, String destKey) {
return setOperations.intersectAndStore(key, otherKey,
destKey);
}
/**
* key集合與多個集合的交集存儲到destKey集合中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
@Override
public Long sIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return setOperations.intersectAndStore(key, otherKeys,
destKey);
}
/**
* 獲取兩個集合的并集
*
* @param key
* @param otherKeys
* @return
*/
@Override
public Set<Object> sUnion(String key, String otherKeys) {
return setOperations.union(key, otherKeys);
}
/**
* 獲取key集合與多個集合的并集
*
* @param key
* @param otherKeys
* @return
*/
@Override
public Set<Object> sUnion(String key, Collection<String> otherKeys) {
return setOperations.union(key, otherKeys);
}
/**
* key集合與otherKey集合的并集存儲到destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
@Override
public Long sUnionAndStore(String key, String otherKey, String destKey) {
return setOperations.unionAndStore(key, otherKey, destKey);
}
/**
* key集合與多個集合的并集存儲到destKey中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
@Override
public Long sUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return setOperations.unionAndStore(key, otherKeys, destKey);
}
/**
* 獲取兩個集合的差集
*
* @param key
* @param otherKey
* @return
*/
@Override
public Set<Object> sDifference(String key, String otherKey) {
return setOperations.difference(key, otherKey);
}
/**
* 獲取key集合與多個集合的差集
*
* @param key
* @param otherKeys
* @return
*/
@Override
public Set<Object> sDifference(String key, Collection<String> otherKeys) {
return setOperations.difference(key, otherKeys);
}
/**
* key集合與otherKey集合的差集存儲到destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
@Override
public Long sDifference(String key, String otherKey, String destKey) {
return setOperations.differenceAndStore(key, otherKey,
destKey);
}
/**
* key集合與多個集合的差集存儲到destKey中
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
@Override
public Long sDifference(String key, Collection<String> otherKeys,
String destKey) {
return setOperations.differenceAndStore(key, otherKeys,
destKey);
}
/**
* 獲取集合所有元素
*
* @param key
* @return
*/
@Override
public Set<Object> setMembers(String key) {
return setOperations.members(key);
}
/**
* 隨機獲取集合中的一個元素
*
* @param key
* @return
*/
@Override
public Object sRandomMember(String key) {
return setOperations.randomMember(key);
}
/**
* 隨機獲取集合中count個元素
*
* @param key
* @param count
* @return
*/
@Override
public List<Object> sRandomMembers(String key, long count) {
return setOperations.randomMembers(key, count);
}
/**
* 隨機獲取集合中count個元素并且去除重復的
*
* @param key
* @param count
* @return
*/
@Override
public Set<Object> sDistinctRandomMembers(String key, long count) {
return setOperations.distinctRandomMembers(key, count);
}
/**
* @param key
* @param options
* @return
*/
@Override
public Cursor<Object> sScan(String key, ScanOptions options) {
return setOperations.scan(key, options);
}
/**------------------zSet相關操作--------------------------------*/
/**
* 添加元素,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @param score
* @return
*/
@Override
public Boolean zAdd(String key, String value, double score) {
return zSetOperations.add(key, value, score);
}
/**
* @param key
* @param values
* @return
*/
@Override
public Long zAdd(String key, Set<ZSetOperations.TypedTuple<Object>> values) {
return zSetOperations.add(key, values);
}
/**
* @param key
* @param values
* @return
*/
@Override
public Long zRemove(String key, Object... values) {
return zSetOperations.remove(key, values);
}
/**
* 增加元素的score值,并返回增加后的值
*
* @param key
* @param value
* @param delta
* @return
*/
@Override
public Double zIncrementScore(String key, String value, double delta) {
return zSetOperations.incrementScore(key, value, delta);
}
/**
* 返回元素在集合的排名,有序集合是按照元素的score值由小到大排列
*
* @param key
* @param value
* @return 0表示第一位
*/
@Override
public Long zRank(String key, Object value) {
return zSetOperations.rank(key, value);
}
/**
* 返回元素在集合的排名,按元素的score值由大到小排列
*
* @param key
* @param value
* @return
*/
@Override
public Long zReverseRank(String key, Object value) {
return zSetOperations.reverseRank(key, value);
}
/**
* 獲取集合的元素, 從小到大排序
*
* @param key
* @param start 開始位置
* @param end 結束位置, -1查詢所有
* @return
*/
@Override
public Set<Object> zRange(String key, long start, long end) {
return zSetOperations.range(key, start, end);
}
/**
* 獲取集合元素, 并且把score值也獲取
*
* @param key
* @param start
* @param end
* @return
*/
@Override
public Set<ZSetOperations.TypedTuple<Object>> zRangeWithScores(String key, long start,
long end) {
return zSetOperations.rangeWithScores(key, start, end);
}
/**
* 根據Score值查詢集合元素
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
@Override
public Set<Object> zRangeByScore(String key, double min, double max) {
return zSetOperations.rangeByScore(key, min, max);
}
/**
* 根據Score值查詢集合元素, 從小到大排序
*
* @param key
* @param min 最小值
* @param max 最大值
* @return
*/
@Override
public Set<ZSetOperations.TypedTuple<Object>> zRangeByScoreWithScores(String key,
double min, double max) {
return zSetOperations.rangeByScoreWithScores(key, min, max);
}
/**
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
@Override
public Set<ZSetOperations.TypedTuple<Object>> zRangeByScoreWithScores(String key,
double min, double max, long start, long end) {
return zSetOperations.rangeByScoreWithScores(key, min, max, start, end);
}
/**
* 獲取集合的元素, 從大到小排序
*
* @param key
* @param start
* @param end
* @return
*/
@Override
public Set<Object> zReverseRange(String key, long start, long end) {
return zSetOperations.reverseRange(key, start, end);
}
/**
* 獲取集合的元素, 從大到小排序, 并返回score值
*
* @param key
* @param start
* @param end
* @return
*/
@Override
public Set<ZSetOperations.TypedTuple<Object>> zReverseRangeWithScores(String key,
long start, long end) {
return zSetOperations.reverseRangeWithScores(key, start, end);
}
/**
* 根據Score值查詢集合元素, 從大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
@Override
public Set<Object> zReverseRangeByScore(String key, double min,
double max) {
return zSetOperations.reverseRangeByScore(key, min, max);
}
/**
* 根據Score值查詢集合元素, 從大到小排序
*
* @param key
* @param min
* @param max
* @return
*/
@Override
public Set<ZSetOperations.TypedTuple<Object>> zReverseRangeByScoreWithScores(
String key, double min, double max) {
return zSetOperations.reverseRangeByScoreWithScores(key,min, max);
}
/**
* 根據Score值查詢集合元素, 從大到小排序
*
* @param key
* @param min
* @param max
* @param start
* @param end
* @return
*/
@Override
public Set<Object> zReverseRangeByScore(String key, double min,
double max, long start, long end) {
return zSetOperations.reverseRangeByScore(key, min, max,start, end);
}
/**
* 根據score值獲取集合元素數量
*
* @param key
* @param min
* @param max
* @return
*/
@Override
public Long zCount(String key, double min, double max) {
return zSetOperations.count(key, min, max);
}
/**
* 獲取集合大小
*
* @param key
* @return
*/
@Override
public Long zSize(String key) {
return zSetOperations.size(key);
}
/**
* 獲取集合大小
*
* @param key
* @return
*/
@Override
public Long zZCard(String key) {
return zSetOperations.zCard(key);
}
/**
* 獲取集合中value元素的score值
*
* @param key
* @param value
* @return
*/
@Override
public Double zScore(String key, Object value) {
return zSetOperations.score(key, value);
}
/**
* 移除指定索引位置的成員
*
* @param key
* @param start
* @param end
* @return
*/
@Override
public Long zRemoveRange(String key, long start, long end) {
return zSetOperations.removeRange(key, start, end);
}
/**
* 根據指定的score值的范圍來移除成員
*
* @param key
* @param min
* @param max
* @return
*/
@Override
public Long zRemoveRangeByScore(String key, double min, double max) {
return zSetOperations.removeRangeByScore(key, min, max);
}
/**
* 獲取key和otherKey的并集并存儲在destKey中
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
@Override
public Long zUnionAndStore(String key, String otherKey, String destKey) {
return zSetOperations.unionAndStore(key, otherKey, destKey);
}
/**
* @param key
* @param otherKeys
* @param destKey
* @return
*/
@Override
public Long zUnionAndStore(String key, Collection<String> otherKeys,
String destKey) {
return zSetOperations.unionAndStore(key, otherKeys, destKey);
}
/**
* 交集
*
* @param key
* @param otherKey
* @param destKey
* @return
*/
@Override
public Long zIntersectAndStore(String key, String otherKey,
String destKey) {
return zSetOperations.intersectAndStore(key, otherKey, destKey);
}
/**
* 交集
*
* @param key
* @param otherKeys
* @param destKey
* @return
*/
@Override
public Long zIntersectAndStore(String key, Collection<String> otherKeys,
String destKey) {
return zSetOperations.intersectAndStore(key, otherKeys, destKey);
}
/**
* @param key
* @param options
* @return
*/
@Override
public Cursor<ZSetOperations.TypedTuple<Object>> zScan(String key, ScanOptions options) {
return zSetOperations.scan(key, options);
}
/**
* ------------------pipelined相關操作--------------------------------
*/
@Override
public void removeList(String key, List<String> values) {
redisTemplate.executePipelined(new SessionCallback<Object>() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
values.stream().forEach(value -> operations.opsForList().remove(key, 0, value));
return null;
}
});
// redisTemplate.executePipelined(new RedisCallback<String>() {
// @Override
// public String doInRedis(RedisConnection conn) throws DataAccessException {
// values.stream().forEach(value -> conn.lRem(key.getBytes(StandardCharsets.UTF_8), 0, value.getBytes(StandardCharsets.UTF_8)));
// return null;
// }
// });
}
/**
* ------------------scan相關操作--------------------------------
*/
@Override
public void scanKeys(String pattern){
ScanOptions options = ScanOptions.scanOptions().match(pattern + "*").count(3).build(); // 調整count以適應你的需求
Cursor<byte[]> cursor = redisTemplate.executeWithStickyConnection(new RedisCallback<Cursor<byte[]>>() {
@Override
public Cursor<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {
return connection.scan(options);
}
});
while (cursor.hasNext()) {
byte[] keyBytes = cursor.next();
String key = new String(keyBytes, StandardCharsets.UTF_8); // 將字節數組轉換為字符串
// 在這里處理鍵
System.out.println("Key: " + key);
}
cursor.close();
}
}
以上完整的方案實現了Spring Boot
與Redis
單機、集群、哨兵模式的無縫集成,開發者可根據實際需求靈活切換模式,快速應用到項目開發中。
責任編輯:武曉燕
來源:
一安未來