栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合Redis详细笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合Redis详细笔记

一、引入依赖

    org.springframework.boot
    spring-boot-starter-data-redis

二、修改application.yml
spring:
    redis:
      host: 127.0.0.1 #主机地址
      port: 6379 #端口号
      password: 123456 #密码(没有则不写)
      jedis:
        pool:
          max-active: 8
          max-wait: -1
          max-idle: 500
          min-idle: 0
      lettuce:
        shutdown-timeout: 0
三、引入配置文件
package com.hq.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    
    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}
四、注入RedisTemplet
import org.springframework.data.redis.core.RedisTemplate;

@Autowired
private RedisTemplate redisTemplate;
五、通用操作

使用方式:redisTemplate.方法名();

1、判断key是否存在

方法如下

public Boolean hasKey(K key);

key:key名
2、指定key失效时间
public Boolean expire(K key, long timeout, TimeUnit unit);

key:key名
timeout:时间
unit:时间单位
3、获取key失效时间 1)、单位为秒
public Long getExpire(K key);

key:key名
返回值:还有多少秒过期,如果为-2,则key不存在,如果为-1,则key永久生效。
2)、指定单位
public Long getExpire(K key, final TimeUnit timeUnit);

key:key名
timeUnit:时间单位
返回值:还有多久过期,如果为-2,则key不存在,如果为-1,则key永久生效。
4、删除缓存
//参数为String
Boolean delete(K key);
返回值:是否删除成功

//参数为集合
Long delete(Collection keys);
返回值:删除成功的数量
5、设置在什么时候过期
public Boolean expireAt(K key, Date date)

key:key名
date:具体时间
6、将当前数据库的 key 移动到指定定的数据库中
public Boolean move(K key, int dbIndex);

key:key名
dbIndex:库序号,从0开始
7、设置key永久生效
public Boolean persist(K key);
8、随机获取一个key
public K randomKey();

返回值:key名
9、查找匹配的key
public Set keys(K pattern);

pattern:正则表达式
返回值:满足条件的Set集合
10、修改key名
public void rename(K oldKey, K newKey);

oldKey:要修改的key名
newKey:新的key名
11、仅当 newkey 不存在时,将 oldKey 改名为 newkey
public Boolean renameIfAbsent(K oldKey, K newKey);

oldKey:要修改的key名
newKey:新的key名
12、返回key的类型
public DataType type(K key);

返回值:key的类型
六、String操作

使用方式:redisTemplate.opsForValue().方法名();

1、设值
void set(K var1, V var2);

var1:key名
var2:值
2、取值
V get(Object var1);
3、批量设值
void multiSet(Map var1);

参数说明:map的每一对键值对将设置为redis的键值
4、批量取值
List multiGet(Collection var1);

var1:key集合
返回值:值集合
5、获取旧值并设置新值
V getAndSet(K var1, V var2);

var1:key名
var2:新值
返回值:旧值
6、获取旧值并删除(版本6.0.6)
V getAndDelete(K key);
7、当 键不存在时设值
Boolean setIfAbsent(K var1, V var2);

var1:key名
var2:值
8、当键存在时设值
Boolean setIfPresent(K var1, V var2);

var1:key名
var2:值s
9、批量设置多个 键值 对,当给的 key 都不存在才会设置成功
Boolean multiSetIfAbsent(Map var1);

参数说明:map的每一对键值对将设置为redis的键值
10、自增长, 负数则为自减
Long increment(K var1, long var2);

var1:key名
var2:需要自增或自减的值
返回值:自增或自减后的值
11、自增长, 负数则为自减(浮点数)
Double increment(K var1, double var2);

var1:key名
var2:需要自增或自减的值
返回值:自增或自减后的值
12、追加字符串
Integer append(K var1, String var2);

var1:key名
var2:需要追加的内容
返回值:追加值后新值的长度
16、获取指定索引的字符串
String get(K key, long start, long end);

key:key名
start:开始索引
end:结束索引
17、将指定索引的值替换成任意值
void set(K key, V value, long offset);

key:key名
value:值
offset:索引
18、获取字符串长度
Long size(K key);
七、Hash操作

使用方式:redisTemplate.opsForHash().方法名();

1、获取指定字段的值
HV get(H var1, Object var2);

var1:key名
var2:字段名
返回值:值
2、根据key获取所有键值对
Map entries(H var1);

var1:key名
返回值:键值对
3、获取所有给定字段的值
List multiGet(H var1, Collection var2);

var1:key名
var2:字段名集合
返回值:对应的值集合
4、设置一个键值对
void put(H var1, HK var2, HV var3);

var1:key名
var2:字段名
var3:值
5、批量设置键值对
void putAll(H var1, Map var2);

var1:key名
var2:多个键值对
6、当key不存在时才设置
Boolean putIfAbsent(H var1, HK var2, HV var3);

var1:key名
var2:字段名
var3:值
7、删除任意个字段
Long delete(H var1, Object... var2);

var1:key名
var2:多个字段名
返回值:删除的字段个数
8、查询指定字段是否存在
Boolean hasKey(H var1, Object var2);

var1:key名
var2:字段名
9、指定指定自增,负数则为自减
Long increment(H var1, HK var2, long var3);

var1:key名
var2:字段名
var3:自增或自减值
返回值:自增或自减后的值
10、指定指定自增,负数则为自减(浮点数)
Double increment(H var1, HK var2, double var3);

var1:key名
var2:字段名
var3:自增或自减值
返回值:自增或自减后的值
11、获取所有字段
Set keys(H var1);

var1:key名
返回值:字段名集合
12、获取字段数量
Long size(H var1);

var1:key名
返回值:字段数量
13、获取所有值
List values(H var1);

var1:key名
返回值:值集合
八、List操作

使用方式:redisTemplate.opsForList().方法名();

1、将值放入list尾部
Long rightPush(K key, V value);

key:key名
value:值
返回值:集合的总数量
2、批量将值放入list尾部
//参数为可变参数
Long rightPushAll(K key, V... values);

//参数为集合
Long rightPushAll(K key, Collection values)

返回值:均为list的总数量	
3、将值放入list头部
Long leftPush(K key, V pivot, V value);

key:key名
value:值
返回值:集合的总数量
4、批量将值放入list头部
//参数为可变几何
Long rightPushAll(K key, V... values);

//参数为集合
Long rightPushAll(K key, Collection values);

返回值:均为list的总数量
5、通过索引获取list的值
V index(K key, long index);

key:key名
index:索引,当index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
6、获取list的长度
Long size(K key);

返回值:list的长度
7、获取给定范围的值
List range(K key, long start, long end);

key:key名
start:起始索引
end:结束索引 0到-1代表所有值
8、根据索引修改list中的某条数据
void set(K key, long index, V value);

key:key名
index:索引
value:值
9、移除N个值
Long remove(K key, long count, Object value);

key:key名
count:需要移除的数量 count > 0 从表头删除,count < 0 从表尾删除,count=0全部删除
value:需要移除的值
返回值:成功移除的数量
10、只保留list中给定范围的元素,其他全部删除
void trim(K key, long start, long end);

key:key名
start:开始索引
end:结束索引
11、从左边获取并移除第一个元素
V leftPop(K key);
12、从左边批量获取并移除元素
List leftPop(K key, long count);
13、从左边获取并移除第一个元素,直到成功获取或等到超时为止
V leftPop(K var1, long var2, TimeUnit var4);

var1:key名
var2:数值
var4:时间单位
14、从右边获取并移除第一个元素
V rightPop(K key);
15、从右边边批量获取并移除元素
List rightPop(K key, long count);
16、从左边获取并移除第一个元素,直到成功获取或等到超时为止
V rightPop(K var1, long var2, TimeUnit var4);

var1:key名
var2:数值
var4:时间单位
17、移除列表的最后一个元素,并将该元素添加到另一个列表并返回
V rightPopAndLeftPush(K var1, K var2);

var1:需要移除的key
var2:需要添加的key
返回值:被移除的元素
18、移除列表的最后一个元素,并将该元素添加到另一个列表并返回,如果没有元素则等待超时或直到有元素为止
V rightPopAndLeftPush(K var1, K var2, long var3, TimeUnit var5);

var1:需要移除的key
var2:需要添加的key
var3:数值
var5:时间单位
返回值:被移除的元素
九、Set操作

使用方式:redisTemplate.opsForSet().方法名();

1、添加元素
Long add(K key, V... values);

返回值:添加成功的元素总数
2、移除元素
Long remove(K key, Object... values);

返回值:移除成功的元素总数
3、移除并获取一个随机元素
V pop(K key);
4、批量获取并移除随机元素
List pop(K key, long count);

key:key名
count:数量
5、将元素 value 从一个集合移到另一个集合
Boolean move(K key, V value, K destKey);

key:需要从哪个key移动值
value:需要移动的值
destKey:需要移动到哪个key
6、获取集合的大小
Long size(K key);
7、判断集合是否包含 value
Boolean isMember(K key, Object o);
8、交集 1)、获取两个集合的交集
Set intersect(K key, K otherKey);
2)、获取key集合与多个集合的交集
Set intersect(K key, Collection otherKeys);
3)、key 集合与 otherKey 集合的交集存储到 destKey 集合中
Long intersectAndStore(K key, Collection otherKeys, K destKey);
4、key 集合与多个集合的交集存储到 destKey 集合中
Long intersectAndStore(K var1, Collection var2, K var3);
9、并集 1)、获取两个集合的并集
Set union(K key, K otherKey);
2)、获取key集合与多个集合的并集
Set union(K key, Collection otherKey);
3)、key 集合与 otherKey 集合的并集存储到 destKey 中
Long unionAndStore(K key, K otherKey, K destKey);
4)、key 集合与多个集合的并集存储到 destKey 中
Long unionAndStore(K key, Collection var2, K destKey);
10、差集 1)、获取两个集合的差集
Set difference(K key, K otherKey);

返回值:key-otherKey的差集
2)、获取 key 集合与多个集合的差集
Set difference(K key, Collection otherKeys);
3)、key 集合与 otherKey 集合的差集存储到 destKey 中
Long differenceAndStore(K key, K otherKey, K destKey);
4)、key 集合与多个集合的差集存储到 destKey 中
Long differenceAndStore(K key, Collection otherKeys, K destKey);

返回值:destKey集合的长度
11、获取集合所有元素
Set members(K key);
12、随机获取集合中的一个元素
V randomMember(K key);
13、随机获取集合中 count 个元素
List randomMembers(K key, long count);
十、zSet操作

使用方式:redisTemplate.opsForZSet().方法名();

1、添加元素
Boolean add(K key, V value, double score);

key:key名
value:值
score:排序值
返回值:是否添加成功
2、批量添加元素
Long add(K key, Set> tuples);
3、移除有序集合的值
Long remove(K key, Object... values);
4、增加元素的 score 值,并返回增加后的值
Double incrementScore(K key, V value, double delta);

key:key名
value:值
delta:需要增加的score值
返回值:增加后的值
5、获得元素在集合的排名(score从小到大)
Long rank(K key, Object o);
6、获取元素在集合的排序(score从大到小)
Long reverseRank(K key, Object o);
7、获取集合元素(score从小到大)
Set range(K key, long start, long end);

key:key名
start:开始索引
end:结束索引 -1 表示从开始位置到后面的所有元素
返回值:元素集合
8、获取集合元素, 并且把 score 值也获取
Set> rangeWithScores(K key, long start, long end);

key:key名
start:开始索引
end:结束索引 -1 表示从开始位置到后面的所有元素
返回值:元素集合
9、根据 score 值查询元素(升序)
Set rangeByScore(K key, double min, double max);

key:key名
min:最小值
max:最大值
返回值:在最小值与最大值之间的元素集合
10、根据 score 值查询集合元素及score(score从小到大)
Set> rangeByScoreWithScores(K key, double min, double max);

key:key名
min:最小值
max:最大值
返回值:在最小值与最大值之间的元素集合
11、获取集合的元素(降序)
Set reverseRange(K key, long start, long end);

key:key名
start:开始索引
end:结束索引
12、获取集合的元素 并返回 score 值(降序)
Set> reverseRangeWithScores(K key, long start, long end);

key:key名
start:开始索引
end:结束索引
13、根据score查询集合元素(降序)
Set reverseRangeByScore(K key, double min, double max);

key:key名
min:最小值
max:最大值
返回值:分数在 min 与 max 之间的元素的集合, 按分数倒序
14、根据 score 查询集合元素并获取score(降序)
Set> reverseRangeByScoreWithScores(K key, double min, double max);

key:key名
min:最小值
max:最大值
返回值:分数在 min 与 max 之间的元素的集合, 按分数倒序
15、根据 score 值获取集合元素数量
Long count(K key, double min, double max);

key:key名
min:最小值
max:最大值
返回值:分数在 min 与 max 之间的元素数量
16、获取集合大小
Long size(K key);
17、获取集合中 value 元素的 score 值
Double score(K key, Object o);
18、移除指定索引位置的成员
Long removeRange(K key, long start, long end);

key:key名
start:开始索引
end:结束索引
返回值:成功移除的元素个数
19、根据score范围值移除元素
Long removeRangeByScore(K key, double min, double max);

key:key名
start:开始索引
end:结束索引
返回值:成功移除的元素个数
20、交集 1)、获取两个集合的交集并保存在另一个集合
Long intersectAndStore(K key, K otherKey, K destKey);

key:key1
otherKey:key2
destKey:用于保存结果的集合
返回值:新集合的长度
2)、获取 key 和 otherKeys 的交集并存储在 destKey 中
Long intersectAndStore(K key, Collection otherKeys, K destKey);

key:key1
otherKeys:其他集合
destKey:用于保存结果的集合
返回值:新集合的长度
21、并集 1)、获取 key 和 otherKey 的并集并存储在 destKey 中
Long unionAndStore(K key, K otherKey, K destKey);

key:key1
otherKey:key2
destKey:用于保存结果的集合
返回值:新集合的长度
2)、获取 key 和 otherKeys 的并集集并存储在 destKey 中
Long unionAndStore(K key, Collection otherKeys, K destKey);

key:key1
otherKeys:其他集合
destKey:用于保存结果的集合
返回值:新集合的长度
22、差集 1)、获取 key 和 otherKey 的差集并存储在 destKey 中
Long differenceAndStore(K key, K otherKey, K destKey);

key:key1
otherKey:key2
destKey:用于保存结果的集合
返回值:新集合的长度
2)、获取 key 和 otherKeys 的差集集并存储在 destKey 中
Long differenceAndStore(K key, Collection otherKeys, K destKey);

key:key1
otherKeys:其他集合
destKey:用于保存结果的集合
返回值:新集合的长度
十一、Geo操作

使用方式:redisTemplate.opsForGeo().方法名();

1、添加地理位置
Long add(K key, Point point, M member);

key:key名
point:位置(new Point(double x, double y)) x:经度,y:纬度
member:值
2、获取两个元素之间的距离(单位:米)
Distance distance(K key, M member1, M member2);

key:key名
member1:成员1
member2:成员2
返回值:距离,通过.getValue()获取
3、获取两个元素之间的距离(自定义单位)
Distance distance(K key, M member1, M member2, Metric metric);

key:key名
member1:成员1
member2:成员2
metric:单位	   可选值:
				RedisGeoCommands.DistanceUnit.KILOMETERS:千米
                RedisGeoCommands.DistanceUnit.METERS:米
                RedisGeoCommands.DistanceUnit.MILES:英里
                RedisGeoCommands.DistanceUnit.FEET:英尺
返回值:距离,通过.getValue()获取
4、返回给定元素的经纬度
List position(K key, M... members);
5、以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素
GeoResults> radius(K key, Circle within);

key:key名
within:	//经纬度信息
        Point center = new Point(longitude, latitude);
        //距离不超过140KM
        Distance radius = new Distance(140, Metrics.KILOMETERS);
        Circle within = new Circle(center, radius);
返回值:符合条件的元素
6、以给定的经纬度为中心, 返回键包含的位置元素当中, 与中心的距离不超过给定最大距离的所有位置元素,并且根据距离排序并返回距离
GeoResults> radius(K key, Circle within, GeoRadiusCommandArgs args);

key:key名
within:	//经纬度信息
        Point center = new Point(longitude, latitude);
        //距离不超过140KM
        Distance radius = new Distance(140, Metrics.KILOMETERS);
        Circle within = new Circle(center, radius);
args:参考RedisGeoCommands.GeoRadiusCommandArgs args =
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().sortAscending();
		sortDescending()是降序
返回值:符合条件的元素
十二、HyperLogLog操作

使用方式:opsForHyperLogLog().方法名();

1)、添加成员
Long add(K key, V... values);

返回值:至少添加成功1个就返回1,否则为0
2)、获取数量
Long size(K... keys);
3)、删除key
void delete(K key);
4)、获取destination和sourceKeys的并集
Long union(K destination,K... SourceKeys);

返回值:数量
十三、BitMap操作 1、设值bit
使用方式:redisTemplate.opsForValue().setBit(key, offset, value);

方法:Boolean setBit(K key, long offset, boolean value);

key:key名
offset:偏移量
value:true为增加,false为抹去标记
2、判断是否标记过
使用方式:redisTemplate.opsForValue().getBit(key, offest);

方法:Boolean getBit(K key, long offset);

key:key名
offset:偏移量
返回值:是否已标记
3、计数
redisTemplate.execute(new RedisCallback() {
    @Override
    public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
        return redisConnection.bitCount("key".getBytes());
    }
})
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781395.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号