仿黑马点评项目(六、附近商铺GEO)

1.地理坐标搜索技术

GEO数据结构(底层存放地理空间信息的数据使用SortedSet)

2.导入店铺数据到GEO

  • 请求相关的信息
    在这里插入图片描述

    • 请求参数中包含typeId商户类型、current页码,滚动查询(没向下拉动就再查询一页)、x经度、y纬度,返回值是符合要求的商户信息List
    • 关于用户的地理坐标,一般是由前台获取手机的地理坐标信息,现在这里写死在前端页面
  • 存储店铺信息到Redis的GEO数据结构中

    • 因为MySQL数据库不能实现范围查询,因此首先需要将MySQL的店铺信息导入进Redis当中的GEO数据结构中,因为Redis是内存存储,读写速度较快,因此GEO数据中的value只需要存商铺的id,而score则是店铺的经度x、纬度y转化

    • 需要注意的一点是:在请求中还有商户类型,但在GEO中并没有。因此,按照店铺的类型做分组,类型相同的店铺作为同一组,以typeId为key存入同一个GEO集合中即可。

  • 代码实现:
    直接在单元测试中写(模拟后台管理员导入数据)。

// 模拟后端管理员将店铺的地理坐标信息存入Redis中的GEO集合
    @Test
    void loadShopData(){
        // 1.查询店铺信息
        List<Shop> list = shopService.list();
        // 2.把店铺分组,按照 typeId 分组,typeId 一致的放到一个集合
        Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
        // 3.分批完成写入 Redis
        for(Map.Entry<Long, List<Shop>> entry : map.entrySet()){
            // 3.1 获取类型 id
            Long typeId = entry.getKey();
            String key = SHOP_GEO_KEY + typeId;
            // 3.2 获取同类型的店铺集合
            List<Shop> value = entry.getValue();
            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
            // 3.3 写入 redis GEOADD key 经度 纬度 member
            for (Shop shop : value){
                // 一条一条店铺的信息写入效率低
//                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())
                ));
            }
            // 将集合写入到GEO中
            stringRedisTemplate.opsForGeo().add(key, locations);
        }

    }

3.实现附近商铺功能

  • 关于SpringDataRedis版本问题
    SpringDataRedis的2.3.9版本并不支持Redis 6.2提供的GEOSEARCH命令,
    先排除掉spring-data-redis和lettuce的版本,然后新增前两者的版本
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
   <exclusions>
       <exclusion>
           <artifactId>spring-data-redis</artifactId>
           <groupId>org.springframework.data</groupId>
       </exclusion>
       <exclusion>
           <artifactId>lettuce-core</artifactId>
           <groupId>io.lettuce</groupId>
       </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-redis</artifactId>
   <version>2.6.2</version>
</dependency>
<dependency>
   <groupId>io.lettuce</groupId>
   <artifactId>lettuce-core</artifactId>
   <version>6.1.6.RELEASE</version>
</dependency>
  • 代码编写:
    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
) {
   return shopService.queryShopByType(typeId, current, x, y);
}

Service,

@Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null){
            // 不需要坐标查询,按数据库查询
            Page<Shop> page = this.query().eq("type_id", typeId)
                                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        // 2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 3.查询 redis、按照距离排序、分页。结果:shopId、distance
        String key = SHOP_GEO_KEY + typeId;
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        // 此处 limit 一直都是从0开始截取到 end
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));
        // 4.解析出 id
        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {
            // 4.2.获取店铺id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        // 5.根据id查询Shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值