Redis使用Geo数据结构完成同城店铺排序

文章介绍了如何使用Redis的GEO数据结构来存储和检索地理位置信息,特别是针对店铺信息的管理。首先,将店铺经纬度信息存储到Redis,然后通过`georadius`命令进行范围查询。对于分页,文章提出了一种基于距离排序和流式处理的解决方案,通过跳跃分页并按顺序查询数据库来确保结果的正确排序。
摘要由CSDN通过智能技术生成

在黑马点评中,有个功能是按照地理位置查找附店铺
在这里插入图片描述
查看网页请求发送格式:
在这里插入图片描述
请求参数:
在这里插入图片描述
发送展示店铺类型id(食品,玩乐,旅游…)以及当前经纬度坐标
所以按照接口要求我们实现该功能
在实现该功能时候我们需要了解redis的GEO数据结构

GEO数据结构

相关命令:
在这里插入图片描述
geoadd :添加一个geo结构 以及成员名字和经纬度
这里我们添加俩个地方经纬度:北京bj,上海 sh
在这里插入图片描述
geopos:获取地理位置的坐标。
在这里插入图片描述
返回的是经纬度:
在这里插入图片描述
geodist:计算两个位置之间的距离。
在这里插入图片描述
georadius:根据用户给定的经纬度坐标来获取指定范围内的地理位置
参数说明:

m :米,默认单位。
km :千米。
mi :英里。
ft :英尺。
WITHDIST: 在返回位置元素的同时, 将位置元素与中心之间的距离也一并返回。
WITHCOORD: 将位置元素的经度和纬度也一并返回。
WITHHASH: 以 52 位有符号整数的形式, 返回位置元素经过原始 geohash 编码的有序集合分值。 这个选项主要用于底层应用或者调试, 实际中的作用并不大。
COUNT 限定返回的记录数。
ASC: 查找结果根据距离从近到远排序。
DESC: 查找结果根据从远到近排序。
在这里插入图片描述
在这里插入图片描述
查看redisInsight:
在这里插入图片描述
可以发现geo底层存储方式是sorted set(zset) 排序分数score是经纬度 转化后的hash值

其他的命令这里不会使用到 有需要可以了解
GEO的命令使用方法
以上操作我们就可以完成相关操作了
首先把地图的店铺信息导入redis:

//        1.查询所有店铺id
        List<Shop> shops = shopservice.list();
//        2.对店铺信息进行分组 typeid一致的放入一个集合
        Map<Long, List<Shop>> map = shops.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//        3.分批完成出差存储写入
        for ( Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            //3.1获取类型id
            Long typeId = entry.getKey();
            String key="shop:geo:"+typeId;

            //         3.2   获取同类型的店铺集合
            List<Shop> value = entry.getValue();
            List<RedisGeoCommands.GeoLocation<String>> locations=new ArrayList<>(value.size());
//     3.3       写入redis geoadd key 经纬度
            for(Shop shop:value){
                //for循环写入所有店铺的地址
//                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);
        }
    }

写入后:
在这里插入图片描述

controller对应路径方法


    /**
     * 根据商铺类型分页查询商铺信息
     * @param typeId 商铺类型
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/of/type")
    public Result queryShopByType(
            @RequestParam("typeId") Integer typeId,
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ,@RequestParam(value = "x",required = false) Double x,@RequestParam(value = "y",required = false) Double y) {
//      前端可能发送店铺第地址,可能不是按照地址位置排序 required 参数填写false
        return  shopService.queryShopByType(typeId, current, x, y);

    }

service

public interface IShopService extends IService<Shop> {

    Result queryById(Long id);

    Result update(Shop shop);

    Result queryShopByType(Integer typeId, Integer current, Double x, Double y);
}

serviceimp

    /**todo 1.1日的任务根据种类·分页查询 有可能根据地址 也可能不是
     * 根据商品种类排序
     * @param typeId 种类
     * @param current 当前页号
     * @param x 经度
     * @param y 维度
     * @return
     */
    @Override
    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.MAX_PAGE_SIZE));
//          1.2  返回数据
            return  Result.ok(page);
        }
       //  2. 计算分页参数
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;//从哪里开始 SystemConstants.DEFAULT_PAGE_SIZE=5
          int end=current* SystemConstants.DEFAULT_PAGE_SIZE;    //从哪里结束
//       3. 查询redis 根据距离排序 ,分页 得到shopId:dist Distance(5000) 默认单位m
        String key=HmConstants.SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().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();//从0 到end的分页
        if(content.size()<from){
//            查询到的店铺小于分页的起点  没有下一页了 结束
            return  Result.ok(Collections.emptyList());
        }
//     4.1   我们需要截取从from到end的部分
        List<Long> ids=new ArrayList<>(content.size());//创建id 集合集合收集便利的id
        Map<String,Distance> distanceMap=new HashMap<>(content.size());//创建相应集合的集合存放距离
        //跳跃2分页查询
     content.stream().skip(from).forEach(result->{
//        4.2 获取店铺id
         String shopId = result.getContent().getName();
         ids.add(Long.valueOf(shopId));
//         4.3获取距离
         Distance distance = result.getDistance();
         distanceMap.put(shopId,distance);//一个店铺,和一对应距离对应
     });
//       5. 根据id查询店铺  保证有序
        String joinids = StrUtil.join(",",ids);//把集合拼接
//        5.1 sql order by 完成有序凭借
        List<Shop> shopList = query().in("id", ids).last("order by field (id," + joinids + ")").list();
        for (Shop shop : shopList)
        {
            // 5.2便利 为集合设置距离
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shopList);
    }

ps:
这里有几个重点:
1.这里把店铺分类+id和业务前缀作为key存储
在这里插入图片描述

2.search操作对应stringRedisTemplate.opsForGeo().search方法

//       3. 查询redis 根据距离排序 ,分页 得到shopId:dist
        String key=HmConstants.SHOP_GEO_KEY+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));//分别是键,圆心,半径,距离,搜索参数

参数:
在这里插入图片描述
//分别是Geo键,圆心,半径,距离,搜索参数

其中RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
是逻辑分页 只分页了0到结束位置 显然不符合我们要求
所以使用stream流跳跃查询

     //  2. 计算分页参数
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;//从哪里开始
          int end=current* SystemConstants.DEFAULT_PAGE_SIZE;    //从哪里结束
/     4.1   我们需要截取从from到end的部分
        List<Long> ids=new ArrayList<>(content.size());//创建id 集合集合收集便利的id
        Map<String,Distance> distanceMap=new HashMap<>(content.size());//创建相应集合的集合存放距离
        //跳跃2分页查询
     content.stream().skip(from).forEach(result->{
//        4.2 获取店铺id
         String shopId = result.getContent().getName();
         ids.add(Long.valueOf(shopId));
//         4.3获取距离
         Distance distance = result.getDistance();
         distanceMap.put(shopId,distance);//一个店铺,和一对应距离对应
     });
  1. 专门创建参数 ids 集合 和map存放距离和店铺id对应
    因为mp中的querybybatchids批量查询是无序的 需要我们·自己凭借条件
 //       5. 根据id查询店铺  保证有序
        String joinids = StrUtil.join(",",ids);//把集合拼接
//        5.1 sql order by 完成有序凭借
        List<Shop> shopList = query().in("id", ids).last("order by field (id," + joinids + ")").list();

而distancemap是存放每个店铺和当前位置的距离(圆心传过来的xy参数)
解析数据的时候存入map

content.stream().skip(from).forEach(result->{
//        4.2 获取店铺id
         String shopId = result.getContent().getName();
         ids.add(Long.valueOf(shopId));
//         4.3获取距离
         Distance distance = result.getDistance();
         distanceMap.put(shopId,distance);//一个店铺,和一对应距离对应
     });
   List<Shop> shopList = query().in("id", ids).last("order by field (id," + joinids + ")").list();
  for (Shop shop : shopList)
        {
            // 5.2便利 为集合设置距离
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

为批量查询的店铺数据设置距离
MP中数据实体类·和表是一对一的,因为表中没有距离,是为了实现该功能添加的我们需要设置·在注解标识

 @TableField(exist = false)
    private Double distance;

完成结果:
在这里插入图片描述
以上就是根据前端传递当前位置的精度维度进行位置查找附附近店铺位置的解决方法,仅供参考逻辑,具体代码根据业务不同

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝胖子不是胖子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值