14、Redis进阶:RedisTemplate操作Redis之API详解

StringRedisTemplate

由于存储在Redis中的键和值非常普遍java.lang.String,因此Redis模块提供了RedisConnection和的两个扩展RedisTemplate,分别是StringRedisConnection(及其DefaultStringRedisConnection实现),并且StringRedisTemplate是用于密集型String操作的便捷的一站式解决方案。除了绑定到String键之外,模板和连接还使用StringRedisSerializer下方,这意味着存储的键和值是人类可读的(假设Redis和您的代码使用相同的编码)。

StringRedisTemplate 继承了RedisTemplate类,只是所有的KV序列化都设置为 StringRedisSerializer.UTF_8。

public class StringRedisTemplate extends RedisTemplate<String, String> {
   
     
    public StringRedisTemplate() {
   
     
        this.setKeySerializer(RedisSerializer.string());
        this.setValueSerializer(RedisSerializer.string());
        this.setHashKeySerializer(RedisSerializer.string());
        this.setHashValueSerializer(RedisSerializer.string());
    }

    public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
   
     
        this();
        this.setConnectionFactory(connectionFactory);
        this.afterPropertiesSet();
    }

    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
   
     
        return new DefaultStringRedisConnection(connection);
    }
}

测试案例

    @Test
    void stringRedisTemplateTest() {
   
     
        stringRedisTemplate.boundValueOps("kkk").set("vvv");
        String value = stringRedisTemplate.boundValueOps("kkk").get();

        stringRedisTemplate.boundHashOps("hashkkk").putIfAbsent("kkk","vvv");
        System.out.println(value);
    }

查看redis中的数据,发现都为String,很方便阅读:
*

RedisTemplate

Operations

RedisTemplate对Redis的每种数据类型都提供了响应的Operation对象,对数据进行操作。
Bound开头需要绑定Key,其对应的操作API都是一样的
*
*

    @Test
    void operationsTest(){
   
     
        // Key-Value
        BoundValueOperations<String, Object> boundValueOperations = redisTemplate.boundValueOps("key");
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // List
        BoundListOperations<String, Object> boundListOperations = redisTemplate.boundListOps("list:key");
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();
        // Set
        BoundSetOperations<String, Object> boundSetOperations = redisTemplate.boundSetOps("set:key");
        SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
        // Zset
        BoundZSetOperations<String, Object> boundZSetOps = redisTemplate.boundZSetOps("zset:key");
        ZSetOperations<String, Object> zSetOperations = redisTemplate.opsForZSet();
        // Hash
        BoundHashOperations<String, Object, Object> boundHashOperations = redisTemplate.boundHashOps("hash:key");
        HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash();
        // BitMaps (无)
        // HyperLogLog
        HyperLogLogOperations<String, Object> hyperLogLogOperations = redisTemplate.opsForHyperLogLog();
        // Stream
        BoundStreamOperations<String, Object, Object> boundStreamOperations = redisTemplate.boundStreamOps("stream:key");
        StreamOperations<String, Object, Object> streamOperations = redisTemplate.opsForStream();
        // Geo
        BoundGeoOperations<String, Object> boundGeoOperations = redisTemplate.boundGeoOps("geo:key");
        GeoOperations<String, Object> geoOperations = redisTemplate.opsForGeo();
    }

BoundValueOperations

        // Key-Value
        BoundValueOperations<String, Object> boundValueOperations = redisTemplate.boundValueOps("key");
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 设定key对应的vlaue值
        boundValueOperations.set("set");
        // 将value值从第offset位开始替换
        boundValueOperations.set("oop", 1);
        // 设置value并设置过期时间1小时
        boundValueOperations.set("ooo", Duration.ofHours(1));
        // 设置value并设置过期时间3600秒
        boundValueOperations.set("opo", 3600, TimeUnit.SECONDS);
        // 返回key对应的value
        Object value = boundValueOperations.get();
        System.out.println("value:" + value);
        // 从0开始,到1结束,截取value的值
        String valueOfSub = boundValueOperations.get(0, 1);
        System.out.println("valueOfSub:" + valueOfSub);
        // 替换value的值,并且返回value的旧值
        Object oldValue = boundValueOperations.getAndSet("new");
        System.out.println("oldValue" + oldValue);

        // 判断key是否有对应的value,如果有,则返回false,如果没有,添加,返回true
        Boolean setIfAbsent = boundValueOperations.setIfAbsent("setIfAbsent");
        System.out.println("setIfAbsent" + setIfAbsent);
        // 判断当前的键的值是否为v,是的话不作操作,不实的话进行替换。如果没有这个键也不会做任何操作。
        Boolean setIfPresent = boundValueOperations.setIfPresent("setIfPresent");
        System.err.println("setIfPresent" + setIfPresent);

        // 在value值后面进行添加,并且返回新value的长度
        Integer append = boundValueOperations.append("append");
        System.out.println("append" + append);
        // 返回value的长度
        Long size = boundValueOperations.size();
        System.out.println("size" + size);
        // 返回key的剩余缓存时间,单位:秒
        Long expire = boundValueOperations.getExpire();
        System.out.println("expire" + expire);
        // 返回key的名称
        String key = boundValueOperations.getKey();
        System.out.println("key" + key);
        // 返回数据的类型=》string、list。。。
        DataType type = boundValueOperations.getType();
        System.out.println("type" + type.name());

        // 以下会报错,需要配置:redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // INCR: value加1
        boundValueOperations.set(1);
        DataType boundValueOperationsType = boundValueOperations.getType();
        System.out.println("type" + boundValueOperationsType.name());
        Long increment = boundValueOperations.increment();
        System.out.println("increment" + increment);
        // INCR: value加100
        Long increment1 = boundValueOperations.increment(100);
        System.out.println("increment1" + increment1);
        // DECR:value-1
        Long decrement = boundValueOperations.decrement();
        System.out.println("decrement" + decrement);
        // DECR:value-1000
        Long decrement1 = boundValueOperations.decrement(1000);
        System.out.println("decrement1" + decrement1);
        // INCR: value加3.14
        Double increment2 = boundValueOperations.increment(3.14);
        System.out.println("increment2" + increment2);

BoundListOperations

        // List
        BoundListOperations<String, Object> boundListOperations = redisTemplate.boundListOps("list:key");
        ListOperations<String, Object> listOperations = redisTemplate.opsForList();

        // 在List左边添加一个或多个值,返回List的长度
        Long aaa = boundListOperations.leftPush("aaa");
        System.out.println(aaa);
        Long aLong1 = boundListOperations.leftPushAll("ddd", "eee", "fff");
        System.out.println(aLong1);
        // 从左边弹出值
        Object leftPop = boundListOperations.leftPop();
        System.out.println(leftPop);
        Object leftPop1 = boundListOperations.leftPop(Duration.ofMinutes(5L));
        System.out.println(leftPop1);
        Object leftPop2 = boundListOperations.leftPop(1000, TimeUnit.SECONDS);
        System.out.println(leftPop2);
        // 返回List长度
        Long size = boundListOperations.size();
        System.out.println(size);
        // 返回索引为2的值
        Object index = boundListOperations.index(2);
        System.out.println(index);
        // 获取绑定键中给定的区间值,从下标0开始,end可以为-1表示最后一位
        List<Object> range = boundListOperations.range(0, 2);

BoundSetOperations

        // Set
        BoundSetOperations<String, Object> boundSetOperations = redisTemplate.boundSetOps("set:key");
        SetOperations<String, Object> setOperations = redisTemplate.opsForSet();
        // 添加值,可以是集合、数组、多参数
        Long aaa1 = boundSetOperations.add("aaa","bbb");
        // 获取所有值
        Set<Object> members = boundSetOperations.members();
        // 返回第一个集合与其他集合之间的差异,也可以认为说第一个集合中独有的元素
        Set<Object> diff = boundSetOperations.diff("set:diff");
        // 找出两个集合的相同部分
        Set<Object> intersect = boundSetOperations.intersect("set:diff");
        // 找出兩個集合的并集
        Set<Object> union = boundSetOperations.union("union");
        // 返回1位置的值
        Object index1 = boundListOperations.index(1);
        // 移除某个元素
        Long aaa2 = boundSetOperations.remove("aaa");

ZSetOperations

public interface ZSetOperations<K, V> {
   
     
    @Nullable
    Boolean add(K var1, V var2, double var3);

    @Nullable
    Long add(K var1, Set<ZSetOperations.TypedTuple<V>> var2);

    @Nullable
    Long remove(K var1, Object... var2);

    @Nullable
    Double incrementScore(K var1, V var2, double var3);

    @Nullable
    Long rank(K var1, Object var2);

    @Nullable
    Long reverseRank(K var1, Object var2);

    @Nullable
    Set<V> range(K var1, long var2, long var4);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> rangeWithScores(K var1, long var2, long var4);

    @Nullable
    Set<V> rangeByScore(K var1, double var2, double var4);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K var1, double var2, double var4);

    @Nullable
    Set<V> rangeByScore(K var1, double var2, double var4, long var6, long var8);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> rangeByScoreWithScores(K var1, double var2, double var4, long var6, long var8);

    @Nullable
    Set<V> reverseRange(K var1, long var2, long var4);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> reverseRangeWithScores(K var1, long var2, long var4);

    @Nullable
    Set<V> reverseRangeByScore(K var1, double var2, double var4);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K var1, double var2, double var4);

    @Nullable
    Set<V> reverseRangeByScore(K var1, double var2, double var4, long var6, long var8);

    @Nullable
    Set<ZSetOperations.TypedTuple<V>> reverseRangeByScoreWithScores(K var1, double var2, double var4, long var6, long var8);

    @Nullable
    Long count(K var1, double var2, double var4);

    @Nullable
    Long lexCount(K var1, Range var2);

    @Nullable
    Long size(K var1);

    @Nullable
    Long zCard(K var1);

    @Nullable
    Double score(K var1, Object var2);

    @Nullable
    Long removeRange(K var1, long var2, long var4);

    @Nullable
    Long removeRangeByScore(K var1, double var2, double var4);

    @Nullable
    Long unionAndStore(K var1, K var2, K var3);

    @Nullable
    Long unionAndStore(K var1, Collection<K> var2, K var3);

    @Nullable
    default Long unionAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
   
     
        return this.unionAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
    }

    @Nullable
    Long unionAndStore(K var1, Collection<K> var2, K var3, Aggregate var4, Weights var5);

    @Nullable
    Long intersectAndStore(K var1, K var2, K var3);

    @Nullable
    Long intersectAndStore(K var1, Collection<K> var2, K var3);

    @Nullable
    default Long intersectAndStore(K key, Collection<K> otherKeys, K destKey, Aggregate aggregate) {
   
     
        return this.intersectAndStore(key, otherKeys, destKey, aggregate, Weights.fromSetCount(1 + otherKeys.size()));
    }

    @Nullable
    Long intersectAndStore(K var1, Collection<K> var2, K var3, Aggregate var4, Weights var5);

    Cursor<ZSetOperations.TypedTuple<V>> scan(K var1, ScanOptions var2);

    @Nullable
    default Set<V> rangeByLex(K key, Range range) {
   
     
        return this.rangeByLex(key, range, Limit.unlimited());
    }

    @Nullable
    Set<V> rangeByLex(K var1, Range var2, Limit var3);

    @Nullable
    default Set<V> reverseRangeByLex(K key, Range range) {
   
     
        return this.reverseRangeByLex(key, range, Limit.unlimited());
    }

    @Nullable
    Set<V> reverseRangeByLex(K var1, Range var2, Limit var3);

    RedisOperations<K, V> getOperations();

    public interface TypedTuple<V> extends Comparable<ZSetOperations.TypedTuple<V>> {
   
     
        @Nullable
        V getValue();

        @Nullable
        Double getScore();
    }
}

BoundHashOperations

public interface BoundHashOperations<H, HK, HV> extends BoundKeyOperations<H> {
   
     
    @Nullable
    Long delete(Object... var1);

    @Nullable
    Boolean hasKey(Object var1);

    @Nullable
    HV get(Object var1);

    @Nullable
    List<HV> multiGet(Collection<HK> var1);

    @Nullable
    Long increment(HK var1, long var2);

    @Nullable
    Double increment(HK var1, double var2);

    @Nullable
    Set<HK> keys();

    @Nullable
    Long lengthOfValue(HK var1);

    @Nullable
    Long size();

    void putAll(Map<? extends HK, ? extends HV> var1);

    void put(HK var1, HV var2);

    @Nullable
    Boolean putIfAbsent(HK var1, HV var2);

    @Nullable
    List<HV> values();

    @Nullable
    Map<HK, HV> entries();

    Cursor<Entry<HK, HV>> scan(ScanOptions var1);

    RedisOperations<H, ?> getOperations();
}

HyperLogLogOperations

public interface HyperLogLogOperations<K, V> {
   
     
    Long add(K var1, V... var2);

    Long size(K... var1);

    Long union(K var1, K... var2);

    void delete(K var1);
}

BoundStreamOperations

public interface BoundStreamOperations<K, HK, HV> {
   
     
    @Nullable
    Long acknowledge(String var1, String... var2);

    @Nullable
    RecordId add(Map<HK, HV> var1);

    @Nullable
    Long delete(String... var1);

    @Nullable
    String createGroup(ReadOffset var1, String var2);

    @Nullable
    Boolean deleteConsumer(Consumer var1);

    @Nullable
    Boolean destroyGroup(String var1);

    @Nullable
    Long size();

    @Nullable
    default List<MapRecord<K, HK, HV>> range(Range<String> range) {
   
     
        return this.range(range, Limit.unlimited());
    }

    @Nullable
    List<MapRecord<K, HK, HV>> range(Range<String> var1, Limit var2);

    @Nullable
    default List<MapRecord<K, HK, HV>> read(ReadOffset readOffset) {
   
     
        return this.read(StreamReadOptions.empty(), readOffset);
    }

    @Nullable
    List<MapRecord<K, HK, HV>> read(StreamReadOptions var1, ReadOffset var2);

    @Nullable
    default List<MapRecord<K, HK, HV>> read(Consumer consumer, ReadOffset readOffset) {
   
     
        return this.read(consumer, StreamReadOptions.empty(), readOffset);
    }

    @Nullable
    List<MapRecord<K, HK, HV>> read(Consumer var1, StreamReadOptions var2, ReadOffset var3);

    @Nullable
    default List<MapRecord<K, HK, HV>> reverseRange(Range<String> range) {
   
     
        return this.reverseRange(range, Limit.unlimited());
    }

    @Nullable
    List<MapRecord<K, HK, HV>> reverseRange(Range<String> var1, Limit var2);

    @Nullable
    Long trim(long var1);

    @Nullable
    Long trim(long var1, boolean var3);
}

BoundGeoOperations

public interface BoundGeoOperations<K, M> extends BoundKeyOperations<K> {
   
     
    @Nullable
    Long add(Point var1, M var2);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Long geoAdd(Point point, M member) {
   
     
        return this.add(point, member);
    }

    @Nullable
    Long add(GeoLocation<M> var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Long geoAdd(GeoLocation<M> location) {
   
     
        return this.add(location);
    }

    @Nullable
    Long add(Map<M, Point> var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Long geoAdd(Map<M, Point> memberCoordinateMap) {
   
     
        return this.add(memberCoordinateMap);
    }

    @Nullable
    Long add(Iterable<GeoLocation<M>> var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Long geoAdd(Iterable<GeoLocation<M>> locations) {
   
     
        return this.add(locations);
    }

    @Nullable
    Distance distance(M var1, M var2);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Distance geoDist(M member1, M member2) {
   
     
        return this.distance(member1, member2);
    }

    @Nullable
    Distance distance(M var1, M var2, Metric var3);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Distance geoDist(M member1, M member2, Metric metric) {
   
     
        return this.distance(member1, member2, metric);
    }

    @Nullable
    List<String> hash(M... var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default List<String> geoHash(M... members) {
   
     
        return this.hash(members);
    }

    @Nullable
    List<Point> position(M... var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default List<Point> geoPos(M... members) {
   
     
        return this.position(members);
    }

    @Nullable
    GeoResults<GeoLocation<M>> radius(Circle var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default GeoResults<GeoLocation<M>> geoRadius(Circle within) {
   
     
        return this.radius(within);
    }

    @Nullable
    GeoResults<GeoLocation<M>> radius(Circle var1, GeoRadiusCommandArgs var2);

    /** @deprecated */
    @Deprecated
    @Nullable
    default GeoResults<GeoLocation<M>> geoRadius(Circle within, GeoRadiusCommandArgs args) {
   
     
        return this.radius(within, args);
    }

    @Nullable
    GeoResults<GeoLocation<M>> radius(K var1, M var2, double var3);

    /** @deprecated */
    @Deprecated
    @Nullable
    default GeoResults<GeoLocation<M>> geoRadiusByMember(K key, M member, double radius) {
   
     
        return this.radius(key, member, radius);
    }

    @Nullable
    GeoResults<GeoLocation<M>> radius(M var1, Distance var2);

    /** @deprecated */
    @Deprecated
    @Nullable
    default GeoResults<GeoLocation<M>> geoRadiusByMember(M member, Distance distance) {
   
     
        return this.radius(member, distance);
    }

    @Nullable
    GeoResults<GeoLocation<M>> radius(M var1, Distance var2, GeoRadiusCommandArgs var3);

    /** @deprecated */
    @Deprecated
    @Nullable
    default GeoResults<GeoLocation<M>> geoRadiusByMember(M member, Distance distance, GeoRadiusCommandArgs args) {
   
     
        return this.radius(member, distance, args);
    }

    @Nullable
    Long remove(M... var1);

    /** @deprecated */
    @Deprecated
    @Nullable
    default Long geoRemove(M... members) {
   
     
        return this.remove(members);
    }
}

总结

其实和Redis命令差不多,基本上提供了很多操作方法,实在太多了,后面的就懒得写的。。。可以对照Redis命令进行实践。一般实际项目中会自己封装RedisTemplate为工具了,配置一些常用的set\get\expire等操作就行。

版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: