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

一、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 内的所有火车站,并按照距离升序排序

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

二、附加商户搜索

1、先批量导入商户坐标

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

编写测试类实现批量导入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;
 
	/**
 * 根据商铺类型分页查询商铺信息
 * @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);
 }
}

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);
 }
}
作者:卒获有所闻原文地址:https://blog.csdn.net/weixin_54232666/article/details/128767542

%s 个评论

要回复文章请先登录注册