黑马Redis实战项目——黑马点评笔记07 | 附近商户
1、GEO搜索(Redis支持)
2、附近商户搜索
2.1、使用单元测试导入商铺位置信息到Redis
@Test
void loadShop(){
//1 查询店铺信息
List<Shop> list = shopService.list();
//2 把店铺按照typeId分组, typeId一致的放到一个ZSet中
Map<Long,List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//3 分批完成写入
for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
//3.1 获取类型id
Long typeId = entry.getKey();
String key = "shop:geo:"+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())
));
}
//改为批量写入locations集合
stringRedisTemplate.opsForGeo().add(key,locations);
}
}
2.2、实现查找附近商铺功能
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>
//ShopController类中调用queryShopByType方法
/**
* 根据商铺类型分页查询商铺信息
* @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);
}
//IShopService接口中声明queryShopByType方法
Result queryShopByType(Integer typeId, Integer current, Double x, Double y);
queryShopByType方法的难点在于手动逻辑分页
// ShopServiceImpl类中实现queryShopByType方法
@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.DEFAULT_PAGE_SIZE;
int end = current*SystemConstants.DEFAULT_PAGE_SIZE;
//3 查询redis,按照距离排序分页,结果是shopId distance
String key = SHOP_GEO_KEY+typeId;
GeoResults<RedisGeoCommands.GeoLocation<String>> 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查询Shop
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());
HashMap<String, Distance> distanceHashMap = 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();
distanceHashMap.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(distanceHashMap.get(shop.getId().toString()).getValue());
}
return Result.ok(shops);
}