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);
}
}