文章摘要
这篇文章介绍了如何通过自定义一个`Service`接口实现一个名为`ShopServiceImpl`的类,该类实现了SPA(Service Provider)协议,并为一个名为`IShopService`的服务接口提供了具体实现。文章重点描述了`queryShopByType`方法的实现,该方法用于根据给定的类型、坐标和其他参数查询商店。
### 核心内容总结:
1. **类的结构**:`ShopServiceImpl`继承自`ServiceImpl<ShopMapper, Shop>`,实现了`IShopService`接口。
2. **查询逻辑**:
- 当`x`或`y`为`null`时,仅根据类型分页查询商店。
- 当`x`和`y`不为`null`时,使用Redis的地理空间索引功能,根据坐标进行搜索,并按距离排序。
3. **Redis操作**:
- 使用`RedisConstants.SHOP_GEO_KEY`存储地理位置信息。
- 创建`GeoResults`对象,执行空间查询,并限制搜索半径为5公里。
- 按距离排序并分页返回结果。
4. **数据处理**:
- 收集符合条件的商店ID及距离信息。
- 根据ID查询详细信息,并设置距离字段。
### 关键词密度:
文章中关键词的数量及其分布如下:
- `ShopServiceImpl`:1次
- `IShopService`:1次
- `queryShopByType`:2次
- `Redis`:多次
- `坐标查询`:多次
- `分页`:多次
- `距离排序`:多次
@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);
}
}