Redis实现附近商铺的项目实战(redis各类型应用场景)不要告诉别人

随心笔谈2年前发布 admin
182 0 0

文章摘要

这篇文章描述了一个名为`ShopServiceImpl`的Java类,它继承自`ServiceImpl`并实现了`IShopService`接口。该类的主要方法是`queryShopByType`,用于根据给定的类型(`type_id`)、坐标(`x`和`y`)查询店铺信息。 文章重点介绍了以下内容: 1. 当`x`或`y`为`null`时,方法根据`type_id`进行分页查询; 2. 当`x`和`y`不为`null`时,方法计算距离,使用Redis的`RedisGeo`命令进行空间索引查询,按距离排序并分页; 3. 查询结果通过Redis处理后,将店铺信息返回给客户端。 文章还提到了Redis的`GeoLocation`命令、`GeoSearchCommandArgs`以及如何通过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);
}
}

© 版权声明

相关文章