实现某位置附近距离【Redis的GEO】

命令

GEOADD  多个经度(longitude),纬度(latitude),位置名称(member)添加到指定的key中
GEOPOS  从键里面返回所有给定位置元素的位置(经度和纬度)
GEODIST 返回两个给定位置之间的距离
GEORADIUS 以给定的经纬度为中心,返回与中心的距离不超过给定最大距离的所有位置元素
GEORADIUSBYMEMBER 跟GEORADIUS类似
GEOHASH 返回一个或多个位置元素的Geohash表示

命令实操

--添加经纬度坐标   类型是zset
GEOADD city 116.404177 39.909652 "天安门" 116.407991 39.921472 "故宫" 115.939392 40.260532 "长城"

--直接获取所有改city的名称
ZRANGE city 0 -1

--返回经纬度
GEOPOS city 天安门 故宫

--获取坐标hash编码   例如:wx4g0c6ftf0    我们存入的左边redis会自动 转换存在我们的score
GEOHASH city 天安门

--两个位置之间的距离 km,m距离单位
GEODIST city 天安门 长城 km

--以半径为中心,查找附近的xxx (116.412217 39.911402 当前位置)
GEORADIUS city 116.412217 39.911402 10 km withdist withcoord count 10 withhash desc
【 
 WITHDIST:在返回位置元素的同时,将位置素与中心之间的距离也一并返回。距离的单位和用户给定的范围单位保持一致。
 WITHCOORD:将位置元素的经度和维度也一并返回。
 WITHHASH:52位有符号整数的形式,返回位置元素经过原始 geohash编码的有序集合分值。这个选项主要用于底层应用或者调试,实际中的作用并不大
 COUNT: 限定返回的记录数
】

--找出位于指定范围内的元素,中心点是由给定的位置元素决定
GEORADIUSBYMEMBER city 天安门 10 km withdist withcoord count 10 withhash

Java伪代码

提前加载商铺数据,到缓存中存储。【存储数据,当前 商铺的经纬度,商铺id】

     List<Shop> shopList = shopService.list();
    //根据商铺类型分组
    Map<Long, List<Shop>> typeListMap = shopList.stream().collect(Collectors.groupingBy(Shop::getTypeId));

    for (Map.Entry<Long, List<Shop>> entry : typeListMap.entrySet()) {
        //获取类型
        Long typeKey = entry.getKey();
        //获取类型对应店铺
        List<Shop> shops = entry.getValue();
        //key前缀
        String key = "shop:geo:"+typeKey;
        List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(shops.size());
        for (Shop shop : shops) {
            //经度
            //纬度
            //stringRedisTemplate.opsForGeo().add(key,new Point(shop.getX(),shop.getY()),shop.getId().toString());
            locations.add( new RedisGeoCommands.GeoLocation<>(
                    shop.getId().toString(),
                    new Point(shop.getX(),shop.getY())));
        }
        //批量写入
        stringRedisTemplate.opsForGeo().add(
                key,locations
        );
    }


}

/** 入参
1.typeId:商铺类型
2.current:第几页
3.x:当前用户所在经度
4.y:当前用户所在纬度

  public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {

        // 1.判断是否需要根据坐标查询
        if (x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            Result.ok(page.getRecords());
        }
        // 2 计算分页参数
      	 int from = (current - 1 ) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current  * SystemConstants.DEFAULT_PAGE_SIZE;

        //插入当前用户的距离
        Circle circle = new Circle(x, y, Metrics.KILOMETERS.getMultiplier());
        //3 查询redis,按照距离排序 分页 结果 :shopId,distance
        String key = "shop:geo:" + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() //GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .radius(
                    key,
                 circle,
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(end));
        
        /* 使用该方法我们的redis版本必须是redis 6.2.3版本以上的。否则不支持
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() //GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
                .search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));*/



        //4 解析id
        if (results == null){
            return Result.ok(Collections.emptyList());
        }

        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        List<Long> ids = new ArrayList<>(content.size());
        Map<String,Distance> distanceMap = new HashMap<>();
        if (content.size() < from ){
            return Result.ok(Collections.emptyList());
        }
        //截取from — end 的部分
        content.stream().skip(from).forEach(result ->{
            //获取店铺id
            String shipIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shipIdStr));
            //获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shipIdStr,distance);
        });
        //5 根据id查询shop
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();
        // 根据类型分页查询
        // 返回数据
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值