8.附近商户
8.1GEO数据结构的基本用法
- GEO就是Geolocation的简写形式,代表地理坐标。Redis在3.2版本中加入了对GEO的支持,允许存储地理坐标信息,帮助我们根据经纬度来检索数据,常见的命令有
- GEOADD:添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)
- GEOADD:添加一个地理空间信息,包含:经度(longitude)、纬度(latitude)、值(member)
- GEODIST:计算指定的两个点之间的距离并返回
- GEOHASH:将指定member的坐标转化为hash字符串形式并返回
- GEOPOS:返回指定member的坐标
- GEOGADIUS:指定圆心、半径,找到该园内包含的所有member,并按照与圆心之间的距离排序后返回,
6.2之后已废弃
- GEOSEARCH:在指定范围内搜索member,并按照与制定点之间的距离排序后返回,范围可以使圆形或矩形,6.2的新功能
- GEOSEARCHSTORE:与GEOSEARCH功能一致,不过可以把结果存储到一个指定的key,也是6.2的新功能
8.2导入店铺数据到GEO
- 具体场景说明,例如美团/饿了么这种外卖App,你是可以看到商家离你有多远的,那我们现在也要实现这个功能。
- 我们可以使用GEO来实现该功能,以当前坐标为圆心,同时绑定相同的店家类型type,以及分页信息,把这几个条件插入后台,后台查询出对应的数据再返回
- 那现在我们要做的就是:将数据库中的数据导入到Redis中去,GEO在Redis中就是一个member和一个经纬度,经纬度对应的就是tb_shop中的x和y,而member,我们用shop_id来存,因为Redis只是一个内存级数据库,如果存海量的数据,还是力不从心,所以我们只存一个id,用的时候再拿id去SQL数据库中查询shop信息
- 但是此时还有一个问题,我们在redis中没有存储shop_type,无法根据店铺类型来对数据进行筛选,解决办法就是将type_id作为key,存入同一个GEO集合即可
Key | Value | Score |
shop:geo:美食 | 海底捞 | 40691512240174598 |
吉野家 | 40691519846517915 | |
shop:geo:KTV | KTV 01 | 40691165486458787 |
KTV 02 | 40691514154651657 |
@Test
public void loadShopData(){
//1. 查询所有店铺信息
List<Shop> shopList = shopService.list();
//2. 按照typeId,将店铺进行分组
Map<Long, List<Shop>> map = shopList.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//3. 逐个写入Redis
for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
//3.1 获取类型id
Long typeId = entry.getKey();
//3.2 获取同类型店铺的集合
List<Shop> shops = entry.getValue();
String key = SHOP_GEO_KEY + typeId;
for (Shop shop : shops) {
//3.3 写入redis GEOADD key 经度 纬度 member
stringRedisTemplate.opsForGeo().add(key,new Point(shop.getX(),shop.getY()),shop.getId().toString());
}
}
}
- 但是上面的代码不够优雅,是一条一条写入的,效率较低,那我们现在来改进一下,这样只需要写入等同于type_id数量的次数
@Test public void loadShopData() { List<Shop> shopList = shopService.list(); Map<Long, List<Shop>> map = shopList.stream().collect(Collectors.groupingBy(Shop::getTypeId)); for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) { Long typeId = entry.getKey(); List<Shop> shops = entry.getValue(); String key = SHOP_GEO_KEY + typeId; List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>(shops.size()); for (Shop shop : shops) { //将当前type的商铺都添加到locations集合中 locations.add(new RedisGeoCommands.GeoLocation<>(shop.getId().toString(), new Point(shop.getX(), shop.getY()))); } //批量写入 stringRedisTemplate.opsForGeo().add(key, locations); } }
8.3实现附近商户功能
- SpringDataRedis的2.3.9版本并不支持Redis 6.2提供的GEOSEARCH命令,因此我们需要提示其版本,修改自己的pom.xml文件
<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>
- 点击距离分类,查看发送的请求
-
请求网址: http://localhost:8080/api/shop/of/type?&typeId=1¤t=1&x=120.149993&y=30.334229
请求方法: GET
看样子是ShopController中的方法,那我们现在来修改其代码,除了typeId,分页码,我们还需要其坐标
@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);
}
- 具体业务逻辑依旧是写在ShopServiceImpl中
@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.DEFAULT_PAGE_SIZE)); // 返回数据 return Result.ok(page.getRecords()); } //2. 计算分页查询参数 int from = (current - 1) * SystemConstants.MAX_PAGE_SIZE; int end = current * SystemConstants.MAX_PAGE_SIZE; String key = SHOP_GEO_KEY + typeId; //3. 查询redis、按照距离排序、分页; 结果:shopId、distance //GEOSEARCH key FROMLONLAT x y BYRADIUS 5000 m WITHDIST GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(key, GeoReference.fromCoordinate(x, y), new Distance(5000), RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)); if (results == null) { return Result.ok(Collections.emptyList()); } //4. 解析出id List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent(); if (list.size() < from) { //起始查询位置大于数据总量,则说明没数据了,返回空集合 return Result.ok(Collections.emptyList()); } ArrayList<Long> ids = new ArrayList<>(list.size()); HashMap<String, Distance> distanceMap = new HashMap<>(list.size()); list.stream().skip(from).forEach(result -> { String shopIdStr = result.getContent().getName(); ids.add(Long.valueOf(shopIdStr)); Distance distance = result.getDistance(); distanceMap.put(shopIdStr, distance); }); //5. 根据id查询shop String idsStr = StrUtil.join(",", ids); List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD( id," + idsStr + ")").list(); for (Shop shop : shops) { //设置shop的举例属性,从distanceMap中根据shopId查询 shop.setDistance(distanceMap.get(shop.getId().toString()).getValue()); } //6. 返回 return Result.ok(shops); }