LOADING

加载过慢请开启缓存 浏览器默认开启

GEO

2023/8/14 Redis

'image-20221219111217136'

'image-20221219121639587'

List<Shop> list = IShopService.query().list();//查询

Map<Long, List<Shop>> collect = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));//stream

for (Map.Entry<Long, List<Shop>> ListEntry : collect.entrySet()) {
    Long typeId = ListEntry.getKey();
    String key =SHOP_GEO_KEY+typeId;

    List<Shop> value = ListEntry.getValue();

    List<RedisGeoCommands.GeoLocation<String>> locations =new ArrayList<>(value.size());//RedisGeoCommands.GeoLocation<String>

    for (Shop shop : value) {
        locations.add(new RedisGeoCommands.GeoLocation<>(
                shop.getId().toString(),
                new Point(shop.getX(),shop.getY())));
    }

    StringRedisTemplate.opsForGeo().add(key,locations);

}
 public Result queryShopByTyp(Integer typeId, Integer current, Double x, Double y) {
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page);
        }

        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;

        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        String key = SHOP_GEO_KEY + typeId;
        //查询redis、按照距离排序、分页。结果:shopId、distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()//GEOSEARCH
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),//距离
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );

        if (results == null) {
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        //4.1.藏截取from~end的部分
        if (list.size()<from) {
            //没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result -> {//skip截取
        //4.2.获取店铺id
            String shopIdstr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdstr));
        //4.3.获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdstr, distance);
        });
        //5,根据1d查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());
        }

        return Result.ok(shops);
    }