广告
返回顶部
首页 > 资讯 > 数据库 >Redis实现附近商铺的项目实战
  • 858
分享到

Redis实现附近商铺的项目实战

Redis附近商铺Redis附近 2023-01-29 17:01:25 858人浏览 安东尼
摘要

目录一、GEO数据结构1、入门2、练习二、附加商户搜索1、先批量导入商户坐标2、实现附近商户功能一、GEO数据结构 1、入门 GEO是Geolocation的缩写,代表地理坐标。Redis3.2中加入对GEO的支持,允许

一、GEO数据结构

1、入门

GEO是Geolocation的缩写,代表地理坐标。Redis3.2中加入对GEO的支持,允许存储地理坐标信息,帮助我们根据经纬度来检索数据。

常见命令:

  • GEOADD:添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)
  • GEODIST:计算指定的两个点之间的距离并返回
  • GEOHASH:将指定 member 的坐标转为 hash 字符串形式并返回
  • GEOPOS:返回指定 member 的坐标
  • GEORADIUS:指定圆心、半径,找到该圆内包含的所有 member,并按照与圆心之间的距离排序后返回。6.2 以后已废弃
  • GEOSEARCH:在指定范围内搜索 member,并按照与指定点之间的距离排序后返回。范围可以是圆形或矩形。6.2 新功能
  • GEOSEARCHSTORE:与 GEOSEARCH 功能一致,不过可以把结果存储到一个指定的 key。6.2 新功能

2、练习

需求

1、添加下面几条数据:

  • 北京南站(116.378248 39.865275)
  • 北京站(116.42803 39.903738)
  • 北京西站(116.322287 39.893729)

2、计算北京西站到北京站的距离

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

Redis实现附近商铺的项目实战

 搜索10km内有哪些商铺(搜出来的会按照距离排序)和  返回北京站的坐标

Redis实现附近商铺的项目实战

二、附加商户搜索

1、先批量导入商户坐标

按照商户类型做分组,类型相同的商户作为同一组,以 typeId 作为 key 存入同一个 GEO 集合中。

Redis实现附近商铺的项目实战

编写测试类实现批量导入redis中

@SpringBootTest
class HmDianPingApplicationTests {
 
    @Autowired
    private ShopServiceImpl shopService;
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
    @Test
    public 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>> longListEntry : map.entrySet()) {
            Long typeId = longListEntry.geTKEy();
            List<Shop> value = longListEntry.getValue();
            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(value.size());
            for (Shop shop : value) {
                locations.add(new RedisGeoCommands.GeoLocation<>(
                        shop.getId().toString(),
                        new Point(shop.getX(), shop.getY())
                ));
            }
            stringRedisTemplate.opsForGeo().add(RedisConstants.SHOP_GEO_KEY + typeId, locations);
        }
 
    }
}

2、实现附近商户功能

springDataRedis 的 2.3.9 版本并不支持 Redis6.2 提供的 GEOSEARCH 命令,因此我们要把他排除掉,引入我们自己的

<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

前端不一定会传x坐标和y坐标,可能是按照热度等其他条件来查询,所以x和y要required = false,表示可以没有

@RestController
@RequestMapping("/shop")
public class ShopController {
 
    @Resource
    public IShopService shopService;
 
	
    @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

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
 
	@Override
    public Result queryShopByType(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.getRecords());
        }
        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
 
        // 查询 Redis,按照距离排序、分页。
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo().
                search(RedisConstants.SHOP_GEO_KEY + typeId,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
 
        if(search == null){
            return Result.ok(Collections.emptyList());
        }
 
        // 查询 Redis,按照距离排序、分页
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = search.getContent();
        if(from >= content.size()){
            return Result.ok(Collections.emptyList());
        }
 
        List<Long> ids = new ArrayList<>(content.size());
        Map<String, Distance> distanceMap = new HashMap<>(content.size());
        // 截取 from ~ end 的部分
        content.stream().skip(from).forEach(result -> {
            // 获取店铺 id
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            // 获取距离
            Distance distance = result.getDistance();
            distanceMap.put(shopIdStr, distance);
        });
        String join = StrUtil.join(",", ids);
        // 根据 id 查询 shop
        List<Shop> shopList = query().in("id", ids).last("order by field(" + join + ")").list();
 
        for (Shop shop : shopList) {
           shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        
        return Result.ok(shopList);
    }
}

到此这篇关于Redis实现附近商铺的项目实战的文章就介绍到这了,更多相关Redis 附近商铺内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

您可能感兴趣的文档:

--结束END--

本文标题: Redis实现附近商铺的项目实战

本文链接: https://www.lsjlt.com/news/178677.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作