0
点赞
收藏
分享

微信扫一扫

基于Redis的Geo实现附近商铺搜索(含源码)

微信公众号访问地址:基于Redis的Geo实现附近商铺搜索(含源码)

一、GEO常用命令及使用示范

基于Redis的Geo实现附近商铺搜索(含源码)_Geo

1.1、GEO的数据结构

GEO 就是 Geolocation 的简写形式,代表地理坐标。Redis 在 3.2 版本中加入了对 GEO 的支持,允许存储地理坐标信息,帮助我们根据经纬度来检索数据。

常见的命令有:

1、GEOADD:添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)。

案例:添加下面几条数据:

    北京南站(116.378248    39.865275)

    北京站(116.42803     39.903738)

    北京西站(116.322287     39.893729)

0" data-textnode-index-1692415428936="29" data-index-1692415428936="509" data-index-len-1692415428936="509" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>geoadd  g1 116.378248  39.865275 bjnz 116.42803 39.903738 bjz 116.322287 39.893729 bjxz
"3"

2、GEODIST:计算指定的两个点之间的距离并返回。

案例:计算北京西站到北京站的距离

redis6.3:0" data-textnode-index-1692415428936="59" data-index-1692415428936="653" data-index-len-1692415428936="653" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>geodist g1 bjxz bjz km 
"9.0916"
redis6.3:0" data-textnode-index-1692415428936="76" data-index-1692415428936="695" data-index-len-1692415428936="695" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>

3、GEOHASH:将指定 member 的坐标转为 hash 字符串形式并返回.

redis6.3:0" data-textnode-index-1692415428936="83" data-index-1692415428936="747" data-index-len-1692415428936="747" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>geohash g1 bjz
1) "wx4g12k21s0"

4、GEOPOS:返回指定member的坐标

redis6.3:0" data-textnode-index-1692415428936="97" data-index-1692415428936="810" data-index-len-1692415428936="810" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>GEOPOS g1 bjz
1) 1) "116.42802804708480835"
   2) "39.90373880538094653"

5、GEORADIUS:指定圆心、半径,找到该圆内包含的所有 member,并按照与圆心之间的距离排序后返回。(6.2 以后已废弃)

6、GEOSEARCH:在指定范围内搜索 member,并按照与指定点之间的距离排序后返回。范围可以是圆形或矩形。(6.2 新功能)。在Redis中,GEOSEARCH命令用于在地理位置的有序集合中,根据给定的位置信息搜索符合条件的成员。

GEOSEARCH命令的语法如下:

GEOSEARCH key
    [FROMMEMBER member]
    [FROMLONLAT longitude latitude]
    [BYRADIUS radius unit]
    [WITHCOORDINATES]
    [WITHDISTANCES]
    [WITHHASH]
    [COUNT count]
    [ASC|DESC]
    [STORE key]
    [STOREDIST key]

参数说明:

    key:地理位置的有序集合的key名称。

    FROMMEMBER member:从指定成员开始搜索,返回符合条件的成员。

    FROMLONLAT longitude latitude:从给定的经度和纬度开始搜索,返回符合条件的成员。

    BYRADIUS radius unit:根据指定的半径和单位搜索符合条件的成员。

    WITHCOORD:返回成员的经纬度坐标

    WITHDIST:返回成员与中心位置的距离

    WITHHASH:返回成员的地理哈希值

    COUNT count:限制返回的成员数量。

    ASC|DESC:指定返回结果的排序方式,默认为升序

    STORE key:将搜索结果存储到指定的键名中。

    STOREDIST key:将搜索结果存储到指定的键名中,并返回成员与中心位置的距离。

案例:搜索天安门(116.397904 39.909005)附近10km内的所有火车站,并按照距离升序排序。

redis6.3:0" data-textnode-index-1692415428936="201" data-index-1692415428936="1745" data-index-len-1692415428936="1745" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>geosearch g1 fromlonlat 116.397904 39.909005 byradius 10 km withdist
1) 1) "bjz"
   2) "2.6361"


2) 1) "bjnz"
   2) "5.1452"


3) 1) "bjxz"
   2) "6.6723"

7、GEOSEARCHSTORE:与 GEOSEARCH 功能一致,不过可以把结果存储到一个指定的 key。(6.2.新功能)

二、应用案例

基于Redis的Geo实现附近商铺搜索(含源码)_redis_02

1、将店铺信息添加到缓存中

基于Redis的Geo实现附近商铺搜索(含源码)_搜索_03

核心代码:

public void shopDataToRedis() {
        // 1.查询店铺信息
        List<Shop" data-textnode-index-1692415428936="249" data-index-1692415428936="2048" data-index-len-1692415428936="2048" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> list = query().list();
        // 2.把店铺分组,按照typeId分组,typeId一致的放到一个集合
        Map<Long, List<Shop" data-textnode-index-1692415428936="258" data-index-1692415428936="2144" data-index-len-1692415428936="2144" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="258" data-index-1692415428936="2145" data-index-len-1692415428936="2145" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
        // 3.分批完成写入Redis
        for (Map.Entry<Long, List<Shop" data-textnode-index-1692415428936="267" data-index-1692415428936="2277" data-index-len-1692415428936="2277" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="267" data-index-1692415428936="2278" data-index-len-1692415428936="2278" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> entry : map.entrySet()) {
            // 3.1.获取类型id
            Long typeId = entry.getKey();
            String key = SHOP_GEO_KEY + typeId;
            // 3.2.获取同类型的店铺的集合
            List<Shop" data-textnode-index-1692415428936="276" data-index-1692415428936="2469" data-index-len-1692415428936="2469" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> value = entry.getValue();
            List<RedisGeoCommands.GeoLocation<String" data-textnode-index-1692415428936="279" data-index-1692415428936="2548" data-index-len-1692415428936="2548" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="279" data-index-1692415428936="2549" data-index-len-1692415428936="2549" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> locations = new ArrayList<" data-textnode-index-1692415428936="281" data-index-1692415428936="2577" data-index-len-1692415428936="2577" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>(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<" data-textnode-index-1692415428936="291" data-index-1692415428936="2865" data-index-len-1692415428936="2865" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>(
                        shop.getId().toString(),
                        new Point(shop.getX(), shop.getY())
                ));
            }
            stringRedisTemplate.opsForGeo().add(key, locations);
        }
    }

接口调用及结果:

基于Redis的Geo实现附近商铺搜索(含源码)_Geo_04

基于Redis的Geo实现附近商铺搜索(含源码)_redis_05

2、根据商铺类型基于Geo实现附近商铺分页滚动查询

业务流程:

基于Redis的Geo实现附近商铺搜索(含源码)_redis_06

核心代码:

public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1.判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 不需要坐标查询,按数据库查询
            Page<Shop" data-textnode-index-1692415428936="324" data-index-1692415428936="3324" data-index-len-1692415428936="3324" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<" data-textnode-index-1692415428936="330" data-index-1692415428936="3417" data-index-len-1692415428936="3417" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>(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;
        GeoResults<RedisGeoCommands.GeoLocation<String" data-textnode-index-1692415428936="352" data-index-1692415428936="3836" data-index-len-1692415428936="3836" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="352" data-index-1692415428936="3837" data-index-len-1692415428936="3837" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> 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" data-textnode-index-1692415428936="375" data-index-1692415428936="4389" data-index-len-1692415428936="4389" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="375" data-index-1692415428936="4390" data-index-len-1692415428936="4390" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>" data-textnode-index-1692415428936="375" data-index-1692415428936="4391" data-index-len-1692415428936="4391" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> list = results.getContent();
        if (list.size() <= from) {
            // 没有下一页了,结束
            return Result.ok(Collections.emptyList());
        }
        // 4.1.截取 from ~ end的部分
        List<Long" data-textnode-index-1692415428936="389" data-index-1692415428936="4590" data-index-len-1692415428936="4590" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> ids = new ArrayList<" data-textnode-index-1692415428936="391" data-index-1692415428936="4612" data-index-len-1692415428936="4612" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>(list.size());
        Map<String, Distance" data-textnode-index-1692415428936="392" data-index-1692415428936="4655" data-index-len-1692415428936="4655" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> distanceMap = new HashMap<" data-textnode-index-1692415428936="394" data-index-1692415428936="4683" data-index-len-1692415428936="4683" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">>(list.size());
        list.stream().skip(from).forEach(result -" data-textnode-index-1692415428936="397" data-index-1692415428936="4747" data-index-len-1692415428936="4747" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> {
            // 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" data-textnode-index-1692415428936="416" data-index-1692415428936="5103" data-index-len-1692415428936="5103" class="character" style="margin: 0px; padding: 0px; box-sizing: border-box; max-width: 100%; display: inline-block; text-indent: initial;">> 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);
    }

接口调用及展示:

基于Redis的Geo实现附近商铺搜索(含源码)_Geo_07

注意事项:

       SpringDataRedis 的 2.3.9 版本并不支持 Redis 6.2 提供的 GEOSEARCH 命令因此我们需要提示其版本,修改自己的 pom.xml,内容如下:

基于Redis的Geo实现附近商铺搜索(含源码)_redis_08

最终结果展示:

基于Redis的Geo实现附近商铺搜索(含源码)_搜索_09

三、源码获取方式

基于Redis的Geo实现附近商铺搜索(含源码)_搜索_10

说明:后面redis相关操作的功能都会放在此文件夹中,需要相关功能的,只需要获取最新的资源,替换项目即可。

基于Redis的Geo实现附近商铺搜索(含源码)_Geo_11

基于Redis的Geo实现附近商铺搜索(含源码)_搜索_12

基于Redis的Geo实现附近商铺搜索(含源码)_搜索_13

举报

相关推荐

0 条评论