单节点模式
一、引入maven依赖
<parent>
<artifactId>spring-boot-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.2.6.RELEASE</version>
</parent>
<dependencies>
<!--spring-web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- lombok 工具包 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--redis相关新增部分-->
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- lettuce pool -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>
二、application.yaml
配置文件编写
spring:
redis:
host: 127.0.0.1
port: 6379
password: 12345
timeout: 5000
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
三、新增 RedisConfig
配置类
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = getJsonRedisSerializer();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jsonRedisSerializer);
// 支持事物
//template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
/**
* 设置jackson的序列化方式
*/
private Jackson2JsonRedisSerializer<Object> getJsonRedisSerializer() {
Jackson2JsonRedisSerializer<Object> redisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
redisSerializer.setObjectMapper(om);
return redisSerializer;
}
}
四、新增RedisUtil
工具类(可选)
@Component
public class RedisUtil {
private final RedisTemplate<String, Object> redisTemplate;
public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// -------------------key 相关操作---------------------
/**
* 删除 key
*
* @param key 要删除的 键
*/
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 批量删除 key
*
* @param keys 要删除的 键 的集合
*/
public void delete(Collection<String> keys) {
redisTemplate.delete(keys);
}
/**
* 是否存在 key
*
* @param key 判断该 键 是否存在
* @return 存在返回 true, 不存在返回 false
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 设置过期时间
*
* @param key 要设置的 键
* @param timeout 过期时间
* @param unit 时间单位
* @return 设置成功返回 true, 设置失败返回 false
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 设置在什么时间过期
*
* @param key 要设置的 键
* @param date 过期时间
* @return 设置成功返回 true, 设置失败返回 false
*/
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
/**
* 查找匹配的 key
*
* @param pattern 匹配字符串
* @return 满足匹配条件的 键 的 Set 集合
*/
public Set<String> keys(String pattern) {
return redisTemplate.keys(pattern);
}
/**
* 将当前数据库的 key 移动到给定的数据库 db 当中
*
* @param key 要移动的 键
* @param dbIndex 要移动到的 db 的序号, 从 0 开始
* @return 移动成功返回 true, 移动失败返回 false
*/
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
/**
* 移除 key 的过期时间,key 将持久保持
*
* @param key 要移除过期时间的 键
* @return 移除成功返回 true, 并且该 key 将持久存在, 移除失败返回 false
*/
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的过期时间
*
* @param key 要查询剩余过期时间的 键
* @param unit 时间的单位
* @return 剩余的过期时间
*/
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的剩余的过期时间, 默认时间单位: 秒
*
* @param key 要查询剩余过期时间的 键
* @return 剩余的过期时间, 单位: 秒
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
/**
* 从当前数据库中随机返回一个 key
*
* @return 随机获取的 键 的名称
*/
public String randomKey() {
return redisTemplate.randomKey();
}
/**
* 修改 key 的名称
*
* @param oldKey 修改前的 键 的名称
* @param newKey 修改后的 键 的名称
*/
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* 仅当 newkey 不存在时,将 oldKey 改名为 newkey
*
* @param oldKey 修改前的 键 的名称
* @param newKey 修改后的 键 的名称
* @return 修改成功返回 true, 修改失败返回 false
*/
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所储存的值的类型
*
* @param key 要查询类型的 键
* @return key 的数据类型
*/
public DataType type(String key) {
return redisTemplate.type(key);
}
// -------------------string 相关操作---------------------
/**
* 设置指定 key 的值
*
* @param key 要设置的 键
* @param value 要设置的 值
*/
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 获取指定 key 的值
*
* @param key 键 的名称
* @return 键 对应的 值
*/
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 返回 key 的 字符串值 中指定位置的 子字符串
*
* @param key 要获取值的 键
* @param start 开始位置, 最小值: 0
* @param end 结束位置, 最大值: 字符串 - 1, 若为 -1 则是获取整个字符串值
* @return 指定 键 的 字符串值 的 子字符串
*/
public String getRange(String key, long start, long end) {
return redisTemplate.opsForValue().get(key, start, end);
}
/**
* 将给定 key 的值设为 value ,并返回 key 的旧值( old value )
*
* @param key 要设置值的 键
* @param value 新值
* @return 旧值
*/
public Object getAndSet(String key, Object value) {
return redisTemplate.opsForValue().getAndSet(key, value);
}
/**
* 对 key 所储存的字符串值,获取指定偏移量上的位( bit )
*
* @param key 键
* @param offset 偏移量
* @return 指定偏移量上的 位( 0 / 1)
*/
public Boolean getBit(String key, long offset) {
return redisTemplate.opsForValue().getBit(key, offset);
}
/**
* 批量获取 key 的 值
*
* @param keys 要获取值的 键 的集合
* @return key对应的值的集合
*/
public List<Object> multiGet(Collection<String> keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
/**
* 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第 offset 位值变为 value
*
* @param key 要设置的 键
* @param offset 偏移多少位
* @param value 值, true 为 1, false 为 0
* @return 设置成功返回 true, 设置失败返回 false
*/
public Boolean setBit(String key, long offset, boolean value) {
return redisTemplate.opsForValue().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
*/
public void setEx(String key, Object value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
/**
* 只有在 key 不存在时设置 key 的值
*
* @param key 键
* @param value 值
* @return 之前已经存在返回 false, 不存在返回 true
*/
public Boolean setIfAbsent(String key, Object value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始
*
* @param key 键
* @param value 值
* @param offset 从指定位置开始覆写
*/
public void setRange(String key, Object value, long offset) {
redisTemplate.opsForValue().set(key, value, offset);
}
/**
* 获取字符串的长度
*
* @param key 键
* @return 该 key 对应的 值的长度
*/
public Long size(String key) {
return redisTemplate.opsForValue().size(key);
}
/**
* 批量添加 key-value
*
* @param maps key-value 的 map 集合
*/
public void multiSet(Map<String, Object> maps) {
redisTemplate.opsForValue().multiSet(maps);
}
/**
* 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在才会设置成功
*
* @param maps key-value 集合
* @return 之前已经存在返回 false, 不存在返回 true
*/
public Boolean multiSetIfAbsent(Map<String, Object> maps) {
return redisTemplate.opsForValue().multiSetIfAbsent(maps);
}
/**
* 增加(自增长), 负数则为自减
*
* @param key 键
* @param increment 自增量
* @return 增加后的值
*/
public Long incrBy(String key, long increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
* 自增长, 增长量为浮点数
*
* @param key 键
* @param increment 自增量
* @return 增加后的值
*/
public Double incrByFloat(String key, double increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
* 将 value 追加到指定 key 的值的末尾
*
* @param key 键
* @param value 要追加的值
* @return 追加值后新值的长度
*/
public Integer append(String key, String value) {
return redisTemplate.opsForValue().append(key, value);
}
// -------------------hash 相关操作-------------------------
/**
* 获取存储在哈希表中指定字段的值
*
* @param key 键
* @param field 字段名( 即 map 中的 key )
* @return 值
*/
public Object hGet(String key, String field) {
return redisTemplate.opsForHash().get(key, field);
}
/**
* 获取给定 哈希表 中的所有键值对
*
* @param key 哈希表
* @return 所有的 键值对
*/
public Map<Object, Object> hGetAll(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 获取指定 哈希表 中所有给定字段的值
*
* @param key 哈希表
* @param fields 要获取值的字段集合
* @return 哈希表中所有给定字段的值
*/
public List<Object> hMultiGet(String key, Collection<Object> fields) {
return redisTemplate.opsForHash().multiGet(key, fields);
}
/**
* 向指定 哈希表 中存储一个 键值对
*
* @param key 哈希表
* @param hashKey 字段名
* @param value 值
*/
public void hPut(String key, String hashKey, Object value) {
redisTemplate.opsForHash().put(key, hashKey, value);
}
/**
* 向指定 哈希表 中存储多个 键值对
*
* @param key 哈希表
* @param maps 键值对集合
*/
public void hPutAll(String key, Map<String, Object> maps) {
redisTemplate.opsForHash().putAll(key, maps);
}
/**
* 仅当 hashKey 不存在时才设置
*
* @param key 哈希表
* @param hashKey 字段名
* @param value 值
* @return 设置成功返回 true, 设置失败返回 false
*/
public Boolean hPutIfAbsent(String key, String hashKey, Object value) {
return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value);
}
/**
* 删除哈希表中一个或多个字段
*
* @param key 哈希表
* @param fields 要删除的字段集合
* @return 删除成功的数目
*/
public Long hDelete(String key, Object... fields) {
return redisTemplate.opsForHash().delete(key, fields);
}
/**
* 查看哈希表中指定的字段是否存在
*
* @param key 要查看的哈希表
* @param field 字段名
* @return 存在返回 true, 不存在返回 false
*/
public boolean hExists(String key, String field) {
return redisTemplate.opsForHash().hasKey(key, field);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment
*
* @param key 指定的哈希表
* @param field 字段名
* @param increment 增加的量
* @return 增加后的值
*/
public Long hIncrBy(String key, Object field, long increment) {
return redisTemplate.opsForHash().increment(key, field, increment);
}
/**
* 为哈希表 key 中的指定字段的整数值加上增量 increment( 浮点型 )
*
* @param key 指定的哈希表
* @param field 字段名
* @param delta 增加的量( 浮点型 )
* @return 增加后的值
*/
public Double hIncrByFloat(String key, Object field, double delta) {
return redisTemplate.opsForHash().increment(key, field, delta);
}
/**
* 获取所有哈希表中的字段
*
* @param key 哈希表
* @return 所有的 字段
*/
public Set<Object> hKeys(String key) {
return redisTemplate.opsForHash().keys(key);
}
/**
* 获取哈希表中字段的数量
*
* @param key 哈希表
* @return 哈希表所有字段的数量
*/
public Long hSize(String key) {
return redisTemplate.opsForHash().size(key);
}
/**
* 获取哈希表中所有值
*
* @param key 哈希表
* @return 哈希表中所有的值
*/
public List<Object> hValues(String key) {
return redisTemplate.opsForHash().values(key);
}
/**
* 迭代哈希表中的键值对
*
* @param key 哈希表
* @param options 迭代的限制条件, 为 ScanOptions.NONE 则无限制
* @return 下一个键值对元组的游标
*/
public Cursor<Entry<Object, Object>> hScan(String key, ScanOptions options) {
return redisTemplate.opsForHash().scan(key, options);
}
// ------------------------list 相关操作----------------------------
/**
* 通过索引获取列表中的元素
*
* @param key 元素所在的列表
* @param index 下标, 从 0 开始
* @return 列表中指定下标的值
*/
public Object lIndex(String key, long index) {
return redisTemplate.opsForList().index(key, index);
}
/**
* 获取列表指定范围内的元素
*
* @param key 元素所在列表
* @param start 开始位置, 0 是开始位置
* @param end 结束位置, -1 返回所有
* @return 指定索引范围内的元素
*/
public List<Object> lRange(String key, long start, long end) {
return redisTemplate.opsForList().range(key, start, end);
}
/**
* 存储在 list 头部( 左边 )
*
* @param key 列表
* @param value 存储的值
* @return 列表长度
*/
public Long lLeftPush(String key, Object value) {
return redisTemplate.opsForList().leftPush(key, value);
}
/**
* 将多个值存入列表中
*
* @param key 列表
* @param value 值, 可以输入多个
* @return 列表长度
*/
public Long lLeftPushAll(String key, Object... value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
* 将多个值存入列表中
*
* @param key 列表
* @param value 值的集合
* @return 列表长度
*/
public Long lLeftPushAll(String key, Collection<Object> value) {
return redisTemplate.opsForList().leftPushAll(key, value);
}
/**
* 当 list 存在的时候才加入
*
* @param key 列表
* @param value 值
* @return 列表长度
*/
public Long lLeftPushIfPresent(String key, Object value) {
return redisTemplate.opsForList().leftPushIfPresent(key, value);
}
/**
* 如果 pivot 存在,在 pivot 前面添加
*
* @param key 列表
* @param pivot 基准值
* @param value 要添加的值
* @return 列表长度
*/
public Long lLeftPush(String key, Object pivot, Object value) {
return redisTemplate.opsForList().leftPush(key, pivot, value);
}
/**
* 存储在 list 尾部( 右边 )
*
* @param key 列表
* @param value 值
* @return 列表长度
*/
public Long lRightPush(String key, Object value) {
return redisTemplate.opsForList().rightPush(key, value);
}
/**
* 将多个值存入列表中
*
* @param key 列表
* @param value 值, 可以输入多个
* @return 列表长度
*/
public Long lRightPushAll(String key, Object... value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
* 将多个值存入列表中
*
* @param key 列表
* @param value 值的集合
* @return 列表长度
*/
public Long lRightPushAll(String key, Collection<Object> value) {
return redisTemplate.opsForList().rightPushAll(key, value);
}
/**
* 为已存在的列表添加值
*
* @param key 存在的列表
* @param value 值
* @return 列表长度
*/
public Long lRightPushIfPresent(String key, Object value) {
return redisTemplate.opsForList().rightPushIfPresent(key, value);
}
/**
* 在 pivot 元素的右边添加值
*
* @param key 列表
* @param pivot 基准值
* @param value 要添加的值
* @return 列表长度
*/
public Long lRightPush(String key, Object pivot, Object value) {
return redisTemplate.opsForList().rightPush(key, pivot, value);
}
/**
* 通过索引设置列表元素的值
*
* @param key 列表
* @param index 位置
* @param value 值
*/
public void lSet(String key, long index, Object value) {
redisTemplate.opsForList().set(key, index, value);
}
/**
* 移出并获取列表的第一个元素
*
* @param key 列表
* @return 删除的元素
*/
public Object lLeftPop(String key) {
return redisTemplate.opsForList().leftPop(key);
}
/**
* 移出并获取列表的第一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key 列表
* @param timeout 等待时间
* @param unit 时间单位
* @return 删除的元素
*/
public Object lBLeftPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().leftPop(key, timeout, unit);
}
/**
* 移除并获取列表最后一个元素
*
* @param key 列表
* @return 删除的元素
*/
public Object lRightPop(String key) {
return redisTemplate.opsForList().rightPop(key);
}
/**
* 移出并获取列表的最后一个元素, 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param key 列表
* @param timeout 等待时间
* @param unit 时间单位
* @return 删除的元素
*/
public Object lBRightPop(String key, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPop(key, timeout, unit);
}
/**
* 移除列表的最后一个元素,并将该元素添加到另一个列表并返回
*
* @param sourceKey 要移除元素的列表
* @param destinationKey 要添加元素的列表
* @return 移动的元素
*/
public Object lRightPopAndLeftPush(String sourceKey, String destinationKey) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey);
}
/**
* 从列表中弹出一个值,将弹出的元素插入到另外一个列表中并返回它; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
*
* @param sourceKey 要移除元素的列表
* @param destinationKey 要添加元素的列表
* @param timeout 等待时间
* @param unit 时间单位
* @return 移动的元素
*/
public Object lBRightPopAndLeftPush(String sourceKey, String destinationKey, long timeout, TimeUnit unit) {
return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit);
}
/**
* 删除集合中值等于 value 的元素
*
* @param key 列表
* @param index index = 0, 删除所有值等于value的元素;
* index > 0, 从头部开始删除第一个值等于 value 的元素;
* index < 0, 从尾部开始删除第一个值等于 value 的元素;
* @param value 值
* @return 列表长度
*/
public Long lRemove(String key, long index, Object value) {
return redisTemplate.opsForList().remove(key, index, value);
}
/**
* 裁剪 list
*
* @param key 列表
* @param start 起始位置
* @param end 结束位置
* @see <a href="https://redis.io/commands/ltrim">Redis Documentation: LTRIM</a>
*/
public void lTrim(String key, long start, long end) {
redisTemplate.opsForList().trim(key, start, end);
}
/**
* 获取列表长度
*
* @param key 列表
* @return 列表长度
*/
public Long lLen(String key) {
return redisTemplate.opsForList().size(key);
}
// --------------------set 相关操作--------------------------
/**
* set 添加元素
*
* @param key 集合
* @param values 值, 可以同时添加多个
* @return 集合长度
*/
public Long sAdd(String key, Object... values) {
return redisTemplate.opsForSet().add(key, values);
}
/**
* set 移除元素
*
* @param key 集合
* @param values 要移除的元素, 可以同时移除多个
* @return 集合长度
*/
public Long sRemove(String key, Object... values) {
return redisTemplate.opsForSet().remove(key, values);
}
/**
* 移除并返回集合的一个随机元素
*
* @param key 集合
* @return 集合中随机一个元素
*/
public Object sPop(String key) {
return redisTemplate.opsForSet().pop(key);
}
/**
* 将元素 value 从一个集合移到另一个集合
*
* @param key 被移除的集合
* @param value 要移除的元素
* @param destKey 移动到的目标集合
* @return 移动成功返回 true, 移动失败返回 false
*/
public Boolean sMove(String key, Object value, String destKey) {
return redisTemplate.opsForSet().move(key, value, destKey);
}
/**
* 获取集合的大小
*
* @param key 集合
* @return 集合长度
*/
public Long sSize(String key) {
return redisTemplate.opsForSet().size(key);
}
/**
* 判断集合是否包含 value
*
* @param key 集合
* @param value 元素
* @return 包含返回 true, 不包含返回 false
*/
public Boolean sIsMember(String key, Object value) {
return redisTemplate.opsForSet().isMember(key, value);
}
/**
* 获取两个集合的交集
*
* @param key 集合1
* @param otherKey 集合2
* @return 两个集合的交集
*/
public Set<Object> sIntersect(String key, String otherKey) {
return redisTemplate.opsForSet().intersect(key, otherKey);
}
/**
* 获取 key 集合与多个集合的交集
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @return 多个集合的交集
*/
public Set<Object> sIntersect(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().intersect(key, otherKeys);
}
/**
* key 集合与 otherKey 集合的交集存储到 destKey 集合中
*
* @param key 集合1
* @param otherKey 集合2
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sIntersectAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKey,
destKey);
}
/**
* key 集合与多个集合的交集存储到 destKey 集合中
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sIntersectAndStore(String key, Collection<String> otherKeys, String destKey) {
return redisTemplate.opsForSet().intersectAndStore(key, otherKeys,
destKey);
}
/**
* 获取两个集合的并集
*
* @param key 集合1
* @param otherKeys 集合2
* @return 两个集合的并集
*/
public Set<Object> sUnion(String key, String otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* 获取 key 集合与多个集合的并集
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @return 多个集合的并集
*/
public Set<Object> sUnion(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().union(key, otherKeys);
}
/**
* key 集合与 otherKey 集合的并集存储到 destKey 中
*
* @param key 集合1
* @param otherKey 集合2
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey);
}
/**
* key 集合与多个集合的并集存储到 destKey 中
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sUnionAndStore(String key, Collection<String> otherKeys, String destKey) {
return redisTemplate.opsForSet().unionAndStore(key, otherKeys, destKey);
}
/**
* 获取两个集合的差集
*
* @param key 集合1
* @param otherKey 集合2
* @return 集合1 - 集合2 的差集
*/
public Set<Object> sDifference(String key, String otherKey) {
return redisTemplate.opsForSet().difference(key, otherKey);
}
/**
* 获取 key 集合与多个集合的差集
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @return 集合1 - 集合2 - 集合3 - ... 集合n 的差集
*/
public Set<Object> sDifference(String key, Collection<String> otherKeys) {
return redisTemplate.opsForSet().difference(key, otherKeys);
}
/**
* key 集合与 otherKey 集合的差集存储到 destKey 中
*
* @param key 集合1
* @param otherKey 集合2
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sDifference(String key, String otherKey, String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKey,
destKey);
}
/**
* key 集合与多个集合的差集存储到 destKey 中
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long sDifference(String key, Collection<String> otherKeys, String destKey) {
return redisTemplate.opsForSet().differenceAndStore(key, otherKeys,
destKey);
}
/**
* 获取集合所有元素
*
* @param key 集合
* @return 集合中所有元素
*/
public Set<Object> setMembers(String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 随机获取集合中的一个元素
*
* @param key 集合
* @return 集合中随机一个元素
*/
public Object sRandomMember(String key) {
return redisTemplate.opsForSet().randomMember(key);
}
/**
* 随机获取集合中 count 个元素
*
* @param key 集合
* @param count 要获取的元素个数
* @return count 个随机元素组成的集合
*/
public List<Object> sRandomMembers(String key, long count) {
return redisTemplate.opsForSet().randomMembers(key, count);
}
/**
* 随机获取集合中 count 个元素并且去除重复的
*
* @param key 集合
* @param count 要获取的元素个数
* @return count 个随机元素组成的集合, 并且不包含重复元素
*/
public Set<Object> sDistinctRandomMembers(String key, long count) {
return redisTemplate.opsForSet().distinctRandomMembers(key, count);
}
/**
* 迭代集合中的元素
*
* @param key 集合
* @param options 迭代的限制条件, 为 ScanOptions.NONE 则无限制
* @return 下一个元素的游标
*/
public Cursor<Object> sScan(String key, ScanOptions options) {
return redisTemplate.opsForSet().scan(key, options);
}
// ------------------zSet 相关操作--------------------------------
/**
* 添加元素, 有序集合是按照元素的 score 值由小到大排列
*
* @param key 有序集合
* @param value 元素
* @param score 分数
* @return 添加成功返回 true, 添加失败返回 false
*/
public Boolean zAdd(String key, Object value, double score) {
return redisTemplate.opsForZSet().add(key, value, score);
}
/**
* 添加多个元素到有序集合中
*
* @param key 有序集合
* @param values 多个元素值
* @return 有序集合长度
*/
public Long zAdd(String key, Set<TypedTuple<Object>> values) {
return redisTemplate.opsForZSet().add(key, values);
}
/**
* 移除有序集合中的值
*
* @param key 有序集合
* @param values 要移除的值, 可以同时移除多个
* @return 有序集合长度
*/
public Long zRemove(String key, Object... values) {
return redisTemplate.opsForZSet().remove(key, values);
}
/**
* 增加元素的 score 值,并返回增加后的值
*
* @param key 有序集合
* @param value 要增加的元素
* @param delta 增加的分数是多少
* @return 增加后的分数
*/
public Double zIncrementScore(String key, Object value, double delta) {
return redisTemplate.opsForZSet().incrementScore(key, value, delta);
}
/**
* 返回元素在集合的排名,有序集合是按照元素的 score 值由小到大排列
*
* @param key 有序集合
* @param value 值
* @return 排名, 从小到大顺序, 0 表示第一位
*/
public Long zRank(String key, Object value) {
return redisTemplate.opsForZSet().rank(key, value);
}
/**
* 返回元素在集合的排名,按元素的 score 值由大到小排列
*
* @param key 有序集合
* @param value 值
* @return 排名, 从大到小顺序
*/
public Long zReverseRank(String key, Object value) {
return redisTemplate.opsForZSet().reverseRank(key, value);
}
/**
* 获取集合的元素, 从小到大排序
*
* @param key 有序集合
* @param start 开始位置
* @param end 结束位置, -1 表示从开始位置开始后面的所有元素
* @return 指定区间的值的集合
*/
public Set<Object> zRange(String key, long start, long end) {
return redisTemplate.opsForZSet().range(key, start, end);
}
/**
* 获取集合元素, 并且把 score 值也获取
*
* @param key 有序集合
* @param start 开始位置
* @param end 结束位置, -1 表示从开始位置开始后面的所有元素
* @return 指定区间的元素及分数的元组的集合
*/
public Set<TypedTuple<Object>> zRangeWithScores(String key, long start, long end) {
return redisTemplate.opsForZSet().rangeWithScores(key, start, end);
}
/**
* 根据 score 值查询集合元素
*
* @param key 有序集合
* @param min 最小值
* @param max 最大值
* @return 分数 在最小值与最大值之间的元素集合
*/
public Set<Object> zRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().rangeByScore(key, min, max);
}
/**
* 根据 score 值查询集合元素及其分数, 并按分数从小到大排序
*
* @param key 有序集合
* @param min 最小值
* @param max 最大值
* @return 分数 在最小值与最大值之间的元素与分数的元组的集合
*/
public Set<TypedTuple<Object>> zRangeByScoreWithScores(String key, double min, double max) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max);
}
/**
* 根据 score 值查询集合元素及其分数, 从小到大排序, 只获取 start 到 end 位置之间的结果
*
* @param key 有序集合
* @param min 最低分数
* @param max 最高分数
* @param start 开始位置
* @param end 结束位置
* @return 分数在 min 与 max 之间, 位置在 start 与 end 之间的元素与分数的元组的集合
*/
public Set<TypedTuple<Object>> zRangeByScoreWithScores(String key, double min, double max, long start, long end) {
return redisTemplate.opsForZSet().rangeByScoreWithScores(key, min, max, start, end);
}
/**
* 获取集合的元素, 从大到小排序
*
* @param key 有序集合
* @param start 开始位置
* @param end 结束位置
* @return 按照 分数 倒序的元素集合
*/
public Set<Object> zReverseRange(String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRange(key, start, end);
}
/**
* 获取集合的元素, 从大到小排序, 并返回 score 值
*
* @param key 有序集合
* @param start 开始位置
* @param end 结束位置
* @return 指定区间的元素及其分数的元组的集合
*/
public Set<TypedTuple<Object>> zReverseRangeWithScores(String key, long start, long end) {
return redisTemplate.opsForZSet().reverseRangeWithScores(key, start, end);
}
/**
* 根据 score 值查询集合元素, 从大到小排序
*
* @param key 有序集合
* @param min 分数最小值
* @param max 分数最大值
* @return 分数在 min 与 max 之间的元素的集合, 按分数倒序
*/
public Set<Object> zReverseRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max);
}
/**
* 根据 score 值查询集合元素, 从大到小排序
*
* @param key 有序集合
* @param min 分数最小值
* @param max 分数最大值
* @return 分数在 min 与 max 之间的元素与分数的元组的集合, 按分数倒序
*/
public Set<TypedTuple<Object>> zReverseRangeByScoreWithScores(String key, double min, double max) {
return redisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, min, max);
}
/**
* 根据 score 值查询集合元素及其分数, 从小到大排序, 只获取 start 到 end 位置之间的结果, 按分数从小到大排序
*
* @param key 有序集合
* @param min 分数最小值
* @param max 分数最大值
* @param start 开始位置
* @param end 结束位置
* @return 分数在 min 与 max 之间, 位置在 start 与 end 之间的元素与分数的元组的集合, 按分数倒序
*/
public Set<Object> zReverseRangeByScore(String key, double min, double max, long start, long end) {
return redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, start, end);
}
/**
* 根据 score 值获取集合元素数量
*
* @param key 有序集合
* @param min 分数最小值
* @param max 分数最大值
* @return 分数在最小值与最大值之间的元素数量
*/
public Long zCount(String key, double min, double max) {
return redisTemplate.opsForZSet().count(key, min, max);
}
/**
* 获取集合大小( 底层实现还是 zcard )
*
* @param key 有序集合
* @return 集合中的元素数量
*/
public Long zSize(String key) {
return redisTemplate.opsForZSet().size(key);
}
/**
* 获取集合大小
*
* @param key 有序集合
* @return 集合中的元素数量
*/
public Long zZCard(String key) {
return redisTemplate.opsForZSet().zCard(key);
}
/**
* 获取集合中 value 元素的 score 值
*
* @param key 有序集合
* @param value 元素值
* @return 该元素值的分数
*/
public Double zScore(String key, Object value) {
return redisTemplate.opsForZSet().score(key, value);
}
/**
* 移除指定索引位置的成员
*
* @param key 有序集合
* @param start 开始位置
* @param end 结束位置
* @return 移除的元素个数
*/
public Long zRemoveRange(String key, long start, long end) {
return redisTemplate.opsForZSet().removeRange(key, start, end);
}
/**
* 根据指定的 score 值的范围来移除成员
*
* @param key 有序集合
* @param min 分数最小值
* @param max 分数最大值
* @return 移除的元素个数
*/
public Long zRemoveRangeByScore(String key, double min, double max) {
return redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
}
/**
* 获取 key 和 otherKey 的并集并存储在 destKey 中
*
* @param key 集合1
* @param otherKey 集合2
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long zUnionAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey);
}
/**
* 获取 key 和 otherKeys 的并集并存储在 destKey 中
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long zUnionAndStore(String key, Collection<String> otherKeys, String destKey) {
return redisTemplate.opsForZSet().unionAndStore(key, otherKeys, destKey);
}
/**
* 获取 key 和 otherKey 的交集并存储在 destKey 中
*
* @param key 集合1
* @param otherKey 集合2
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long zIntersectAndStore(String key, String otherKey, String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey);
}
/**
* 获取 key 和 otherKeys 的交集并存储在 destKey 中
*
* @param key 集合1
* @param otherKeys 其余多个集合
* @param destKey 用于保存结果的集合
* @return 新集合的长度
*/
public Long zIntersectAndStore(String key, Collection<String> otherKeys, String destKey) {
return redisTemplate.opsForZSet().intersectAndStore(key, otherKeys, destKey);
}
/**
* 迭代有序集合
*
* @param key 有序集合
* @param options 迭代限制条件, 为 ScanOptions.NONE 则无限制
* @return 下一个元素及分数元组的游标
*/
public Cursor<TypedTuple<Object>> zScan(String key, ScanOptions options) {
return redisTemplate.opsForZSet().scan(key, options);
}
}
主从模式
主从模式介绍
主从模式有如下特点:
主从模式是三种模式中最简单的,在主从复制中,数据库分为两类:主数据库 (master) 和从数据库(slave)。
-
主数据库可以进行读写操作,当读写操作导致数据变化时会自动将数据同步给从数据库
-
从数据库一般都是只读的,并且接收主数据库同步过来的数据
-
一个 master 可以拥有多个 slave,但是一个 slave 只能对应一个 master
-
slave 挂了不影响其他 slave 的读和 master 的读和写,重新启动后会将数据从 master 同步过来
-
master 挂了以后,不影响 slave 的读,但 redis 不再提供写服务,master 重启后 redis 将重新对外提供写服务
-
master 挂了以后,不会在 slave 节点中重新选一个 master
工作机制:
当 slave 启动后,主动向 master 发送 SYNC 命令。master 接收到 SYNC 命令后在后台保存快照(RDB 持久化)和缓存保存快照这段时间的命令,然后将保存的快照文件和缓存的命令发送给 slave。slave 接收到快照文件和命令后加载快照文件和缓存的执行命令。
复制初始化后,master 每次接收到的写命令都会同步发送给 slave,保证主从数据一致性。
安全设置:
当 master 节点设置密码后:
-
客户端访问 master 需要密码
-
启动 slave 需要密码,在配置文件中配置即可
-
客户端访问 slave 不需要密码
缺点:
从上面可以看出,master 节点在主从模式中唯一,若 master 挂掉,则 redis 无法对外提供写服务。
主从模式搭建
参考:# redis 主从模式、哨兵模式、集群模式 离线搭建
SpringBoot 进行整合方式
目前大部分整合 redis 主从模式的都是使用 aop 根据查询类型的不同切换数据源 且主从模式 如果主 redis 挂掉的话 不会自动选举从服务器 故弃用
也可采用与《单节点模式》一致的配置使用方式,但是没办法利用“主从模式”的读写分离的特点
哨兵模式(sentinel)
哨兵模式介绍
主从模式的弊端就是不具备高可用性,当 master 挂掉以后,Redis 将不能再对外提供写入操作,因此 sentinel 应运而生。
sentinel 中文含义为哨兵,顾名思义,它的作用就是监控 redis 集群的运行状况,特点如下:
-
sentinel 模式是建立在主从模式的基础上,如果只有一个 Redis 节点,sentinel 就没有任何意义
-
当 master 挂了以后,sentinel 会在 slave 中选择一个做为 master,并修改它们的配置文件,其他 slave 的配置文件也会被修改,比如 slaveof 属性会指向新的 master
-
当 master 重新启动后,它将不再是 master 而是做为 slave 接收新的 master 的同步数据
-
sentinel 因为也是一个进程有挂掉的可能,所以 sentinel 也会启动多个形成一个 sentinel 集群
-
多 sentinel 配置的时候,sentinel 之间也会自动监控
-
当主从模式配置密码时,sentinel 也会同步将配置信息修改到配置文件中,不需要担心
-
一个 sentinel 或 sentinel 集群可以管理多个主从 Redis,多个 sentinel 也可以监控同一个 redis
-
sentinel 最好不要和 Redis 部署在同一台机器,不然 Redis 的服务器挂了以后,sentinel 也挂了
工作机制
-
每个 sentinel 以每秒钟一次的频率向它所知的 master,slave 以及其他 sentinel 实例发送一个 PING 命令
-
如果一个实例距离最后一次有效回复 PING 命令的时间超过 down-after-milliseconds 选项所指定的值, 则这个实例会被 sentinel 标记为主观下线。
-
如果一个 master 被标记为主观下线,则正在监视这个 master 的所有 sentinel 要以每秒一次的频率确认 master 的确进入了主观下线状态
-
当有足够数量的 sentinel(大于等于配置文件指定的值)在指定的时间范围内确认 master 的确进入了主观下线状态, 则 master 会被标记为客观下线
-
在一般情况下, 每个 sentinel 会以每 10 秒一次的频率向它已知的所有 master,slave 发送 INFO 命令
-
当 master 被 sentinel 标记为客观下线时,sentinel 向下线的 master 的所有 slave 发送 INFO 命令的频率会从 10 秒一次改为 1 秒一次
-
若没有足够数量的 sentinel 同意 master 已经下线,master 的客观下线状态就会被移除;
若 master 重新向 sentinel 的 PING 命令返回有效回复,master 的主观下线状态就会被移除
哨兵模式搭建
略。。。。。。
SpringBoot 进行整合的方式
一、引入 redis 相关配置文件
与《单节点模式》一致,直接复用即可,故省略
二、编写 SpringBoot 配置文件
spring:
redis:
password: 12345
timeout: 5000
sentinel:
master: mymaster
nodes:
# 注意这里配置的是sentinel节点地址端口,而不是redis master slave的地址端口
- 47.116.114.234:44801
- 139.224.249.155:44801
- 47.116.113.67:44801
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
三、编写 redis 配置类(配置 redis 序列化方式)
与《单节点模式》一致,直接复用即可,故省略
四、新增RedisUtil
工具类(可选)
与《单节点模式》一致,直接复用即可,故省略
Cluster 模式
Cluster 模式介绍
sentinel 模式基本可以满足一般生产的需求,具备高可用性。但是当数据量过大到一台服务器存放不下的情况时,主从模式或 sentinel 模式就不能满足需求了,这个时候需要对存储的数据进行分片,将数据存储到多个 Redis 实例中。cluster 模式的出现就是为了解决单机 Redis 容量有限的问题,将 Redis 的数据根据一定的规则分配到多台机器。
cluster 可以说是 sentinel 和主从模式的结合体,通过 cluster 可以实现主从和 master 重选功能,所以如果配置两个副本三个分片的话,就需要六个 Redis 实例。因为 Redis 的数据是根据一定规则分配到 cluster 的不同机器的,当数据量过大时,可以新增机器进行扩容。
- 使用集群,只需要将 redis 配置文件中的
cluster-enable
配置打开即可。每个集群中至少需要三个主数据库才能正常运行,新增节点非常方便。 - 多个 redis 节点网络互联,数据共享
- 所有的节点都是一主一从(也可以是一主多从),其中从不提供服务,仅作为备用
- 不支持同时处理多个 key(如 MSET/MGET),因为 redis 需要把 key 均匀分布在各个节点上, 并发量很高的情况下同时创建 key-value 会降低性能并导致不可预测的行为
- 支持在线增加、删除节点
- 客户端可以连接任何一个主节点进行读写
Cluster 模式搭建
SpringBoot 进行整合的方式
一、引入 redis 相关配置文件
与《单节点模式》一致,直接复用即可,故省略
二、编写 SpringBoot 配置文件
spring:
redis:
database: 0
password: 12345678
timeout: 5000
cluster:
max-redirects: 3
nodes:
- 47.116.114.234:54801
- 47.116.114.234:54802
- 139.224.249.155:54801
- 139.224.249.155:54802
- 101.132.222.76:54801
- 101.132.222.76:54802
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
三、编写 redis 配置类(配置 redis 序列化方式)
与《单节点模式》对应部分完全一致,故省略
四、RedisUtil 工具类(可选)
与《单节点模式》对应部分完全一致,故省略