RedisTemplate方法詳解


RedisTemplate方法詳解

 

 maven依賴

        <!--redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--<version>2.1.4.RELEASE</version>-->
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

 

redis序列化方式配置

@Configuration
public class RedisConfig {

    /**
     * 設置Redis序列化方式,默認使用的JDKSerializer的序列化方式,效率低,這里我們使用 FastJsonRedisSerializer
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        // key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // value序列化
        redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
        // Hash key序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash value序列化
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

 

1:Redis的String數據結構 

設置當前的key以及value值

redisTemplate.opsForValue().set(key, value) redisTemplate.opsForValue().set("num","123");

設置當前的key以及value值並且設置過期時間

redisTemplate.opsForValue().set(key, value, timeout, unit) redisTemplate.opsForValue().set("num","123",10, TimeUnit.SECONDS);

TimeUnit.DAYS //天
TimeUnit.HOURS //小時
TimeUnit.MINUTES //分鍾
TimeUnit.SECONDS //秒
TimeUnit.MILLISECONDS //毫秒

將舊的key設置為value,並且返回舊的key(設置key的字符串value並返回其舊值)

redisTemplate.opsForValue().getAndSet(key, value);

在原有的值基礎上新增字符串到末尾

redisTemplate.opsForValue().append(key, value)

獲取字符串的長度

redisTemplate.opsForValue().size(key)

重新設置key對應的值,如果存在返回false,否則返回true

redisTemplate.opsForValue().setIfAbsent(key, value)

設置map集合到redis

Map valueMap = new HashMap(); valueMap.put("valueMap1","map1"); valueMap.put("valueMap2","map2"); valueMap.put("valueMap3","map3"); redisTemplate.opsForValue().multiSet(valueMap); 

如果對應的map集合名稱不存在,則添加否則不做修改

Map valueMap = new HashMap(); valueMap.put("valueMap1","map1"); valueMap.put("valueMap2","map2"); valueMap.put("valueMap3","map3"); redisTemplate.opsForValue().multiSetIfAbsent(valueMap); 

通過increment(K key, long delta)方法以增量方式存儲long值(正值則自增,負值則自減)

redisTemplate.opsForValue().increment(key, increment);

批量獲取值

public List<String> multiGet(Collection<String> keys) {
    return redisTemplate.opsForValue().multiGet(keys);
 }

返回傳入key所存儲的值的類型

redisTemplate.type(key);

修改redis中key的名稱

 public void renameKey(String oldKey, String newKey) { redisTemplate.rename(oldKey, newKey); }

如果舊值key存在時,將舊值改為新值

public Boolean renameOldKeyIfAbsent(String oldKey, String newKey) { return redisTemplate.renameIfAbsent(oldKey, newKey); }

判斷是否有key所對應的值,有則返回true,沒有則返回false

redisTemplate.hasKey(key)

刪除單個key值

redisTemplate.delete(key)

批量刪除key

redisTemplate.delete(keys) //其中keys:Collection<K> keys

設置過期時間

public Boolean expire(String key, long timeout, TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); }
public Boolean expireAt(String key, Date date) { return redisTemplate.expireAt(key, date); }

返回當前key所對應的剩余過期時間

redisTemplate.getExpire(key);

返回剩余過期時間並且指定時間單位

public Long getExpire(String key, TimeUnit unit) {
    return redisTemplate.getExpire(key, unit);
}

查找匹配的key值,返回一個Set集合類型

public Set<String> getPatternKey(String pattern) { return redisTemplate.keys(pattern); }

將key持久化保存

public Boolean persistKey(String key) { return redisTemplate.persist(key); }

將當前數據庫的key移動到指定redis中數據庫當中

public Boolean moveToDbIndex(String key, int dbIndex) { return redisTemplate.move(key, dbIndex); }

 

2、Hash類型
Redis hash 是一個string類型的field和value的映射表,hash特別適合用於存儲對象。
Redis 中每個 hash 可以存儲 2^32 - 1 鍵值對(40多億)。

 

獲取變量中的指定map鍵是否有值,如果存在該map鍵則獲取值,沒有則返回null。

redisTemplate.opsForHash().get(key, field)

獲取變量中的鍵值對

public Map<Object, Object> hGetAll(String key) { return redisTemplate.opsForHash().entries(key); }

新增hashMap值

redisTemplate.opsForHash().put(key, hashKey, value)

以map集合的形式添加鍵值對

public void hPutAll(String key, Map<String, String> maps) { redisTemplate.opsForHash().putAll(key, maps); }

僅當hashKey不存在時才設置

public Boolean hashPutIfAbsent(String key, String hashKey, String value) { return redisTemplate.opsForHash().putIfAbsent(key, hashKey, value); }

刪除一個或者多個hash表字段

public Long hashDelete(String key, Object... fields) { return redisTemplate.opsForHash().delete(key, fields); }

查看hash表中指定字段是否存在

public boolean hashExists(String key, String field) { return redisTemplate.opsForHash().hasKey(key, field); }

給哈希表key中的指定字段的整數值加上增量increment

public Long hashIncrBy(String key, Object field, long increment) { return redisTemplate.opsForHash().increment(key, field, increment); }
 public Double hIncrByDouble(String key, Object field, double delta) { return redisTemplate.opsForHash().increment(key, field, delta); }

獲取所有hash表中字段

redisTemplate.opsForHash().keys(key)

獲取hash表中存在的所有的值

public List<Object> hValues(String key) { return redisTemplate.opsForHash().values(key); }

獲取hash表中字段的數量

redisTemplate.opsForHash().size(key)

匹配獲取鍵值對,ScanOptions.NONE為獲取全部鍵對

public Cursor<Entry<Object, Object>> hashScan(String key, ScanOptions options) { return redisTemplate.opsForHash().scan(key, options); }

 

3、List類型

通過索引獲取列表中的元素

redisTemplate.opsForList().index(key, index)

獲取列表指定范圍內的元素(start開始位置, 0是開始位置,end 結束位置, -1返回所有)

redisTemplate.opsForList().range(key, start, end)

存儲在list的頭部,即添加一個就把它放在最前面的索引處

redisTemplate.opsForList().leftPush(key, value)

把多個值存入List中(value可以是多個值,也可以是一個Collection value)

redisTemplate.opsForList().leftPushAll(key, value)

List存在的時候再加入

redisTemplate.opsForList().leftPushIfPresent(key, value)

按照先進先出的順序來添加(value可以是多個值,或者是Collection var2)

redisTemplate.opsForList().rightPush(key, value)
redisTemplate.opsForList().rightPushAll(key, value)

設置指定索引處元素的值

redisTemplate.opsForList().set(key, index, value)

移除並獲取列表中第一個元素(如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止)

redisTemplate.opsForList().leftPop(key)
redisTemplate.opsForList().leftPop(key, timeout, unit)

移除並獲取列表最后一個元素

redisTemplate.opsForList().rightPop(key)
redisTemplate.opsForList().rightPop(key, timeout, unit)

從一個隊列的右邊彈出一個元素並將這個元素放入另一個指定隊列的最左邊

redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey)
redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit)

刪除集合中值等於value的元素(index=0, 刪除所有值等於value的元素; index>0, 從頭部開始刪除第一個值等於value的元素; index<0, 從尾部開始刪除第一個值等於value的元素)

redisTemplate.opsForList().remove(key, index, value)

將List列表進行剪裁

redisTemplate.opsForList().trim(key, start, end)

獲取當前key的List列表長度

redisTemplate.opsForList().size(key)

 

4、Set類型

添加元素

redisTemplate.opsForSet().add(key, values)

移除元素(單個值、多個值)

redisTemplate.opsForSet().remove(key, values)

獲取集合的大小

redisTemplate.opsForSet().size(key)

判斷集合是否包含value

redisTemplate.opsForSet().isMember(key, value)

獲取兩個集合的交集(key對應的無序集合與otherKey對應的無序集合求交集)

redisTemplate.opsForSet().intersect(key, otherKey)

獲取多個集合的交集(Collection var2)

redisTemplate.opsForSet().intersect(key, otherKeys)

key集合與otherKey集合的交集存儲到destKey集合中(其中otherKey可以為單個值或者集合)

redisTemplate.opsForSet().intersectAndStore(key, otherKey, destKey)

key集合與多個集合的交集存儲到destKey無序集合中

redisTemplate.opsForSet().intersectAndStore(key, otherKeys, destKey)

獲取兩個或者多個集合的並集(otherKeys可以為單個值或者是集合)

redisTemplate.opsForSet().union(key, otherKeys)

key集合與otherKey集合的並集存儲到destKey中(otherKeys可以為單個值或者是集合)

redisTemplate.opsForSet().unionAndStore(key, otherKey, destKey)

獲取兩個或者多個集合的差集(otherKeys可以為單個值或者是集合)

redisTemplate.opsForSet().difference(key, otherKeys)

差集存儲到destKey中(otherKeys可以為單個值或者集合)

redisTemplate.opsForSet().differenceAndStore(key, otherKey, destKey)

獲取集合中的所有元素

redisTemplate.opsForSet().members(key)

隨機獲取集合中count個元素

redisTemplate.opsForSet().randomMembers(key, count)

隨機獲取集合中的一個元素

redisTemplate.opsForSet().randomMember(key)

遍歷set類似於Interator(ScanOptions.NONE為顯示所有的)

redisTemplate.opsForSet().scan(key, options)

 

 

5、zSet類型

ZSetOperations提供了一系列方法對有序集合進行操作

 添加元素(有序集合是按照元素的score值由小到大進行排列)

redisTemplate.opsForZSet().add(key, value, score)

刪除對應的value,value可以為多個值

redisTemplate.opsForZSet().remove(key, values)

增加元素的score值,並返回增加后的值

redisTemplate.opsForZSet().incrementScore(key, value, delta)

返回元素在集合的排名,有序集合是按照元素的score值由小到大排列

redisTemplate.opsForZSet().rank(key, value)

返回元素在集合的排名,按元素的score值由大到小排列

redisTemplate.opsForZSet().reverseRank(key, value)

獲取集合中給定區間的元素(start 開始位置,end 結束位置, -1查詢所有)

redisTemplate.opsForZSet().reverseRangeWithScores(key, start,end)

按照Score值查詢集合中的元素,結果從小到大排序

redisTemplate.opsForZSet().reverseRangeByScore(key, min, max)

從高到低的排序集中獲取分數在最小和最大值之間的元素

redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, start, end)

根據score值獲取集合元素數量

redisTemplate.opsForZSet().count(key, min, max)

獲取集合的大小

redisTemplate.opsForZSet().size(key)

獲取集合中key、value元素對應的score值

redisTemplate.opsForZSet().score(key, value)

移除指定索引位置處的成員

redisTemplate.opsForZSet().removeRange(key, start, end)

移除指定score范圍的集合成員

redisTemplate.opsForZSet().removeRangeByScore(key, min, max)

獲取key和otherKey的並集並存儲在destKey中(其中otherKeys可以為單個字符串或者字符串集合)

redisTemplate.opsForZSet().unionAndStore(key, otherKey, destKey)

獲取key和otherKey的交集並存儲在destKey中(其中otherKeys可以為單個字符串或者字符串集合)

redisTemplate.opsForZSet().intersectAndStore(key, otherKey, destKey)

遍歷集合(和iterator一模一樣)

Cursor<TypedTuple<Object>> scan = opsForZSet.scan("test3", ScanOptions.NONE); while (scan.hasNext()){ ZSetOperations.TypedTuple<Object> item = scan.next(); System.out.println(item.getValue() + ":" + item.getScore()); }

 

StringRedisTemplate和RedisTemplate區別?

1. 兩者的關系是StringRedisTemplate繼承RedisTemplate。

2. 兩者的數據是不共通的;也就是說StringRedisTemplate只能管理StringRedisTemplate里面的數據,RedisTemplate只能管理RedisTemplate中的數據。

3、序列化方式不一樣:

 RedisTemplate使用的是JdkSerializationRedisSerializer    存入數據會將數據先序列化成字節數組然后在存入Redis數據庫。 

 StringRedisTemplate使用的是StringRedisSerializer

RedisTemplate使用的序列類在在操作數據的時候,比如說存入數據會將數據先序列化成字節數組然后在存入Redis數據庫,這個時候打開Redis查看的時候,你會看到你的數據不是以可讀的形式展現的,而是以字節數組顯示,類似下面

 

 工具類

package com.dw.study.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author
 * @ClassName RedisUtils
 * @Description
 * @Date 2021/1/20 12:22
 * @Version 1.0
 */
@Component
public class RedisUtils {

    private final static Logger log = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


// ##########################【操作String類型】#####################################################

    /**
     * 設置緩存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 設置值並設置過期時間(單位秒)
     *
     * @param key
     * @param value
     * @param time  過期時間
     * @return
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 設置一個已經存在的key的值,並返回舊值
     *
     * @param key
     * @param value
     * @return
     */
    public Object getAndSet(String key, Object value) {
        try {
            Object andSet = redisTemplate.opsForValue().getAndSet(key, value);
            return andSet;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 如果不存在則設置值value,返回true。 否則返回false
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIfAbsent(String key, String value) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 批量設置 k->v 到 redis
     *
     * @param valueMap
     * @return
     */
    public boolean multiSet(HashMap valueMap) {
        try {
            redisTemplate.opsForValue().multiSet(valueMap);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 如果不存在對應的Map,則批量設置 k->v 到 redis
     *
     * @param valueMap
     * @return
     */
    public boolean multiSetIfAbsent(HashMap valueMap) {
        try {
            redisTemplate.opsForValue().multiSetIfAbsent(valueMap);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * 在原有的值基礎上新增字符串到末尾
     *
     * @param key
     * @param value
     * @return
     */
    public boolean append(String key, String value) {
        try {
            redisTemplate.opsForValue().append(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * 獲取value
     *
     * @param key
     * @return
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 批量獲取值
     *
     * @param keys
     * @return
     */
    public List<Object> multiGet(Collection<String> keys) {
        if (CollectionUtils.isEmpty(keys)) {
            return null;
        }
        return redisTemplate.opsForValue().multiGet(keys);
    }


    /**
     * 刪除緩存,支持批量刪除
     *
     * @param key
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
        }
    }

    /**
     * 判斷key是否存在
     *
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 根據key 獲取key的過期時間
     *
     * @param key 鍵 不能為null
     * @return 時間(秒) 返回-1, 代表為永久有效
     */
    public long getKeyExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 指定緩存失效時間
     *
     * @param key  鍵
     * @param time 時間(秒)
     * @return
     */
    public boolean expireKey(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 通過increment(K key, long increment)方法以增量方式存儲long值(正值則自增,負值則自減)
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, long increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * 通過increment(K key, double increment)方法以增量方式存儲double值(正值則自增,負值則自減)
     *
     * @param key
     * @param increment
     * @return
     */
    public void increment(String key, double increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    /**
     * 修改redis中key的名稱
     *
     * @param oldKey
     * @param newKey
     */
    public void renameKey(String oldKey, String newKey) {
        redisTemplate.rename(oldKey, newKey);
    }

    /**
     * 如果舊值key存在時,將舊值改為新值
     *
     * @param oldKey
     * @param newKey
     * @return
     */
    public Boolean renameOldKeyIfAbsent(String oldKey, String newKey) {
        return redisTemplate.renameIfAbsent(oldKey, newKey);
    }

    // ##########################【操作Hash類型】#####################################################

    /**
     * 批量添加Map中的鍵值對
     *
     * @param mapName map名字
     * @param maps
     */
    public boolean hashPutAll(String mapName, Map<String, String> maps) {
        try {
            redisTemplate.opsForHash().putAll(mapName, maps);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * 添加一個鍵值對
     *
     * @param mapName
     * @param key
     * @param value
     */
    public boolean hashPutOne(String mapName, String key, String value) {
        try {
            redisTemplate.opsForHash().put(mapName, key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 添加一個鍵值對,僅當hashKey不存在時才設置
     *
     * @param mapName
     * @param hashKey
     * @param value
     */
    public boolean hashPutOneIfAbsent(String mapName, String hashKey, String value) {
        try {
            redisTemplate.opsForHash().putIfAbsent(mapName, hashKey, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 獲取mapName中的所有的鍵值對
     *
     * @param mapName Map名字
     * @return
     */
    public Object hashGetOne(String mapName, Object hashKey) {
        return redisTemplate.opsForHash().get(mapName, hashKey);
    }

    /**
     * 獲取mapName中的所有的鍵值對
     *
     * @param mapName Map名字
     * @return
     */
    public Map<Object, Object> hashGetAll(String mapName) {
        return redisTemplate.opsForHash().entries(mapName);
    }


    /**
     * 刪除一個或者多個hash表字段
     *
     * @param key
     * @param fields
     * @return
     */
    public Long hashDelete(String key, Object... fields) {
        return redisTemplate.opsForHash().delete(key, fields);
    }

    /**
     * 查看hash表中指定字段是否存在
     *
     * @param key
     * @param field
     * @return
     */
    public boolean hashExists(String key, String field) {
        return redisTemplate.opsForHash().hasKey(key, field);
    }

    /**
     * 給哈希表key中的指定字段的整數值加上增量increment
     *
     * @param key
     * @param field
     * @param increment
     * @return
     */
    public Long hashIncrementByLong(String key, Object field, long increment) {
        return redisTemplate.opsForHash().increment(key, field, increment);
    }

    /**
     * 給哈希表key中的指定字段的double加上增量increment
     *
     * @param key
     * @param field
     * @param delta
     * @return
     */
    public Double hashIncrementByDouble(String key, Object field, double delta) {
        return redisTemplate.opsForHash().increment(key, field, delta);
    }

    /**
     * 獲取hash表中存在的所有的key
     *
     * @param mapName map名字
     * @return
     */
    public Set<Object> hashKeys(String mapName) {
        return redisTemplate.opsForHash().keys(mapName);
    }

    /**
     * 獲取hash表中存在的所有的Value
     *
     * @param mapName map名字
     * @return
     */
    public List<Object> hashValues(String mapName) {
        return redisTemplate.opsForHash().values(mapName);
    }

    /**
     * 獲取hash表的大小
     *
     * @param mapName
     * @return
     */
    public Long hashSize(String mapName) {
        return redisTemplate.opsForHash().size(mapName);
    }

    // ##########################【操作List類型】#####################################################

    /**
     * 設置值到List中的頭部
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean listAddInHead(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 批量設置值到List中的頭部
     *
     * @param key    List名字
     * @param values
     * @return
     */
    public Boolean listAddAllInHead(String key, Collection<Object> values) {
        try {
            redisTemplate.opsForList().leftPushAll(key, values);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 如果存在List->key, 則設置值到List中的頭部
     *
     * @param key   List名字
     * @param value
     * @return
     */
    public Boolean listAddIfPresent(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPushIfPresent(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 設置值到List中的尾部
     *
     * @param key   List名字
     * @param value
     * @return
     */
    public Boolean listAddInEnd(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 批量設置值到List中的尾部
     *
     * @param key    List名字
     * @param values
     * @return
     */
    public Boolean listAddAllInEnd(String key, Collection<Object> values) {
        try {
            redisTemplate.opsForList().rightPushAll(key, values);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 通過索引去設置List->key中的值
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public Boolean listAddByIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }


    /**
     * 根據索引獲取list中的值
     *
     * @param key   list名字
     * @param index
     * @return
     */
    public Object listGetByIndex(String key, long index) {
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * 根據索引范圍獲取list中的值
     *
     * @param key   list名字
     * @param start
     * @param end
     * @return
     */
    public List<Object> listGetByRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 移除並獲取列表中第一個元素(如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止)
     *
     * @param key list名字
     * @return
     */
    public Object listLeftPop(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 移除並獲取列表中最后一個元素(如果列表沒有元素會阻塞列表直到等待超時或發現可彈出元素為止)
     *
     * @param key list名字
     * @return
     */
    public Object listRightPop(String key) {
        return redisTemplate.opsForList().rightPop(key);
    }

    /**
     * 刪除集合中值等於value的元素(
     * index=0, 刪除所有值等於value的元素;
     * index>0, 從頭部開始刪除第一個值等於value的元素;
     * index<0, 從尾部開始刪除第一個值等於value的元素)
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public Long listRemove(String key, long index, Object value) {
        Long removeNum = redisTemplate.opsForList().remove(key, index, value);
        return removeNum;
    }

// ##########################【操作Set類型】#####################################################

    /**
     * 設置值到Set集合(支持批量)
     *
     * @param key
     * @param value
     * @return
     */
    public Boolean setAdd(String key, Object... value) {
        try {
            redisTemplate.opsForSet().add(key, value);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 移除Set集合中的值,支持批量
     *
     * @param key
     * @param values
     * @return 移除的數量
     */
    public long setRemove(String key, Object... values) {
        return redisTemplate.opsForSet().remove(key, values);
    }

    /**
     * 判斷Set中是否存在value
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIsExist(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    // ##########################【操作經緯度】#####################################################

    /***
     * 將指定的地理空間位置(緯度、經度、名稱)添加到指定的key中。
     * @param key redis的key
     * @param longitude   經度
     * @param latitude   緯度
     * @param name  該坐標的名稱(標識)
     * @return
     */
    public Long geoAdd(String key, double longitude, double latitude, String name) {
//        Long addedNum = redisTemplate.opsForGeo().add("city", new Point(116.405285, 39.904989), "北京");
        Long addedNum = redisTemplate.opsForGeo().add(key, new Point(longitude, latitude), name);
        return addedNum;
    }

    /***
     * 從key里返回所有給定位置元素的位置(經度和緯度)。
     * @param key redis的key
     * @param nameList 坐標名稱(標識)的集合
     */
    public List<Point> geoGet(String key, List<String> nameList) {
        List<Point> points = redisTemplate.opsForGeo().position(key, nameList);
        return points;
    }


    /***
     * 【獲取兩個坐標之間的距離】
     * 根據redis中鍵名(key)中,名字為 name1 和 name2 兩個坐標的距離
     * @param key redis的key
     * @param name1 坐標名稱(標識)1
     * @param name2 坐標名稱(標識)2
     * @return distance(單位米)
     */
    public double geoGetDistance(String key, String name1, String name2) {
        double distance = redisTemplate.opsForGeo()
                .distance(key, name1, name2, RedisGeoCommands.DistanceUnit.METERS).getValue();
        return distance;
    }


    /***
     * 【獲取指定范圍內的坐標】
     * 以給定的經緯度為中心畫圓, 返回鍵(key)包含的位置元素當中,
     * 與中心的距離不超過給定最大距離的所有位置元素,並給出所有位置元素與中心的平均距離。
     * @param key redis的key
     * @param longitude   經度
     * @param latitude   緯度
     * @param distance 距離(單位:米)
     * @param count 如果 count > 0 則最多返回count個坐標, 否則返回所有
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoGetCoordinatesWithinRange(String key,
                                                                                         double longitude,
                                                                                         double latitude,
                                                                                         Integer distance,
                                                                                         Integer count) {
        //以當前坐標為中心畫圓,標識當前坐標覆蓋的distance的范圍, Point(經度, 緯度) Distance(距離量, 距離單位)
        Circle circle = new Circle(new Point(longitude, latitude), new Distance(distance, RedisGeoCommands.DistanceUnit.METERS));
        // 從redis獲取的信息包含:距離中心坐標的距離、當前的坐標、並且升序排序,如果count > 0 則只取count個坐標,否則返回所有
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending();
        if (count > 0) {
            args.limit(count);
        }
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo().radius(key, circle, args);
        return radius;
    }

    /***
     * 【獲取指定范圍內的坐標】
     * 以給定的鍵(key)中的坐標名字(標識)name為中心畫圓, 返回鍵包含的位置元素當中,
     * 與中心的距離不超過給定最大距離的所有位置元素,並給出所有位置元素與中心的平均距離。
     * @param key redis的key
     * @param name 坐標名稱(標識)
     * @param distance 距離
     * @param count 如果 count > 0 則最多返回count個坐標, 否則返回所有
     * @return
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoGetCoordinatesWithinRange(String key,
                                                                           String name,
                                                                           Integer distance,
                                                                           Integer count) {
        // 創建距離對象
        Distance distances = new Distance(distance, RedisGeoCommands.DistanceUnit.METERS);
        // 需要從redis獲取的參數
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs
                .newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending();
        if (count > 0) {
            args.limit(count);
        }
        GeoResults<RedisGeoCommands.GeoLocation<Object>> radius = redisTemplate.opsForGeo()
                .radius(key, name, distances, args);
        return radius;
    }


}

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM