从入门到精通,超强 RedisTemplate 方法详解!

你知道的越多,不知道的就越多,业余的像一棵小草!

成功路上并不拥挤,因为坚持的人不多。

编辑:业余草

cnblogs.com/dw3306/p/12840012.html

推荐:https://www.xttblog.com/?p=5231

从入门到精通,超强 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>

引入依赖后,我们需要配置 RedisTemplate。比如:Redis 序列化方式配置。

@Configuration public class RedisConfig { 
 // 设置Redis序列化方式,默认使用的JDKSerializer的序列化方式,效率低,这里我们使用 FastJsonRedisSerializer
    @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;
    }
}

操作 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 所存储的值的类型

修改 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);
}

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);
}

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)

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)

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 查看的时候,你会看到你的数据不是以可读的形式展现的,而是以字节数组显示,类似下面

工具类

@Component 
public class RedisUtils { 
    private final static Logger log = LoggerFactory.getLogger(RedisUtils.class);
    @Autowired 
    private RedisTemplate<String, Object> redisTemplate;

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

    // 设置值并设置过期时间(单位秒)
    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的值,并返回旧值
    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
    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
    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
    public boolean multiSetIfAbsent(HashMap valueMap) { 
        try {
            redisTemplate.opsForValue().multiSetIfAbsent(valueMap); return true;
        } catch (Exception e) {
            log.error(e.getMessage()); return false;
        }
    }

    // 在原有的值基础上新增字符串到末尾
    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
    public Object get(String key) { 
        return key == null ? null : redisTemplate.opsForValue().get(key);
    } 

    // 批量获取值
    public List<Object> multiGet(Collection<String> keys) { 
        if (CollectionUtils.isEmpty(keys)) { r
            eturn null;
        } 
        return redisTemplate.opsForValue().multiGet(keys);
    } 

    // 删除缓存,支持批量删除
    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是否存在
    public boolean hasKey(String key) { 
        try { 
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error(e.getMessage()); return false;
        }
    } 

    // 根据key 获取key的过期时间
    public long getKeyExpire(String key) { 
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    } 

    // 指定缓存失效时间
    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值(正值则自增,负值则自减)
    public void increment(String key, long increment) {
        redisTemplate.opsForValue().increment(key, increment);
    } 

    // 通过increment(K key, double increment)方法以增量方式存储double值(正值则自增,负值则自减)
    public void increment(String key, double increment) {
        redisTemplate.opsForValue().increment(key, increment);
    }

    // 修改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);
    }

    // 批量添加Map中的键值对
    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;
        }
    } 

    // 添加一个键值对
    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不存在时才设置
    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中的所有的键值对
    public Object hashGetOne(String mapName, Object hashKey) { 
        return redisTemplate.opsForHash().get(mapName, hashKey);
    }

    // 获取mapName中的所有的键值对
    public Map<Object, Object> hashGetAll(String mapName) { 
        return redisTemplate.opsForHash().entries(mapName);
    }

    // 删除一个或者多个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 hashIncrementByLong(String key, Object field, long increment) { 
        return redisTemplate.opsForHash().increment(key, field, increment);
    }

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

    // 获取hash表中存在的所有的key
    public Set<Object> hashKeys(String mapName) { 
        return redisTemplate.opsForHash().keys(mapName);
    }

    // 获取hash表中存在的所有的Value
    public List<Object> hashValues(String mapName) { 
        return redisTemplate.opsForHash().values(mapName);
    }

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

    // 设置值到List中的头部
    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中的头部
    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中的头部
    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中的尾部
    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中的尾部
    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中的值
    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中的值
    public Object listGetByIndex(String key, long index) { 
        return redisTemplate.opsForList().index(key, index);
    } 

    // 根据索引范围获取list中的值
    public List<Object> listGetByRange(String key, long start, long end) { 
        return redisTemplate.opsForList().range(key, start, end);
    }

    // 移除并获取列表中第一个元素(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)
    public Object listLeftPop(String key) { r
        eturn redisTemplate.opsForList().leftPop(key);
    }

    // 移除并获取列表中最后一个元素(如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止)
    public Object listRightPop(String key) { 
        return redisTemplate.opsForList().rightPop(key);
    }

    // 删除集合中值等于value的元素
    public Long listRemove(String key, long index, Object value) {
        Long removeNum = redisTemplate.opsForList().remove(key, index, value); 
        return removeNum;
    }

    // 设置值到Set集合(支持批量)
    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集合中的值,支持批量
    public long setRemove(String key, Object... values) { 
        return redisTemplate.opsForSet().remove(key, values);
    }

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

    // 将指定的地理空间位置(纬度、经度、名称)添加到指定的key中。
    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里返回所有给定位置元素的位置(经度和纬度)
    public List<Point> geoGet(String key, List<String> nameList) {
        List<Point> points = redisTemplate.opsForGeo().position(key, nameList); 
        return points;
    } 

    // 根据redis中键名(key)中,名字为 name1 和 name2 两个坐标的距离
    public double geoGetDistance(String key, String name1, String name2) { 
        double distance = redisTemplate.opsForGeo()
                .distance(key, name1, name2, RedisGeoCommands.DistanceUnit.METERS).getValue(); 
                return distance;
    } 

    // 以给定的经纬度为中心画圆, 返回键(key)包含的位置元素当中,与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
    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为中心画圆, 返回键包含的位置元素当中,
     * 与中心的距离不超过给定最大距离的所有位置元素,并给出所有位置元素与中心的平均距离。
     */
    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;
    }

}

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值