主要利用redis3.2后添加的geo
初始化redis中的数据
/**
* 将店铺的id和经纬度存储到redis中
*/
@Test
void geo(){
//1.查询店铺信息
List<Shop> list = shopService.list();
//2.把店铺根据typeid进行分组
Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId));
//分批写入redis
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();
ArrayList<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(key,locations);
}
}
修改pom文件
编写业务层
@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());
}
//2.计算分页参数
int form = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
//查询redis
String key=SHOP_GEO_KEY+typeId;
GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
.search(
key,
GeoReference.fromCoordinate(x, y),
new Distance(5000),
RedisGeoCommands.GeoRadiusCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
);
//解析出id
if (results ==null){
return Result.ok(Collections.emptyList());
}
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
if (list.size()<=form){
// 没有数据
return Result.ok(Collections.emptyList());
}
//4.1截取from-rnd部分
List<Long> ids = new ArrayList<>(list.size());
HashMap<String, Distance> distanceMap = new HashMap<>(list.size());
list.stream().skip(form).forEach(result ->{
//获取店铺id
String shopIdStr = result.getContent().getName();
ids.add(Long.valueOf(shopIdStr));
//4.3 获取距离
Distance distance = result.getDistance();
distanceMap.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(distanceMap.get(shop.getId().toString()).getValue());
}
//返回
return Result.ok(shops);
}