@Test
public void boundGeoOperationsTest() {
BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps("CHINA:CITY");
//南京市 118.803805,32.060168
Point nanjing = new Point(118.803805,32.060168);
//当redis里面已经存在了相同的member的时候,则仅仅更新经纬度
//geoadd:增加某个地理位置的坐标
System.out.println(boundGeoOperations.geoAdd(nanjing, "南京市"));
Point beijing = new Point(116.397039,39.9077);
System.out.println(boundGeoOperations.geoAdd(beijing, "北京市"));
//geodist:获取两个地理位置的距离
Distance distance = boundGeoOperations.geoDist("南京市", "北京市", Metrics.KILOMETERS);
System.out.println("南京市到北京市之间的距离是:" + distance.getValue() + "km");
//geohash:获取某个地理位置的geohash值
List<String> list = boundGeoOperations.geoHash("南京市");
System.out.println("南京市的geoHash = " + list.get(0));
//geopos:获取某个地理位置的坐标
List<Point> pointList = boundGeoOperations.geoPos("南京市");
System.out.println("南京市的经纬度为 = " + pointList.get(0));
//georadius:根据给定地理位置坐标获取指定范围内的地理位置集合
//查询南京市1000KM范围内的城市
Circle within = new Circle(nanjing,1000000);
//设置geo查询参数
RedisGeoCommands.GeoRadiusCommandArgs geoRadiusArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
//查询返回结果包括距离和坐标
geoRadiusArgs = geoRadiusArgs.includeCoordinates().includeDistance();
//按查询出的坐标距离中心坐标的距离进行排序
geoRadiusArgs.sortAscending();
//限制查询返回的数量
geoRadiusArgs.limit(2);
GeoResults<RedisGeoCommands.GeoLocation<String>> geoResults = boundGeoOperations.geoRadius(within,geoRadiusArgs);
List<GeoResult<RedisGeoCommands.GeoLocation<String>>> geoResultList = geoResults.getContent();
for (GeoResult geoResult : geoResultList) {
System.out.println("geoRadius " + geoResult.getContent());
}
//georadiusbymember:根据给定地理位置获取指定范围内的地理位置集合
geoRadiusArgs.limit(1);
geoResults = boundGeoOperations.geoRadiusByMember("南京市",new Distance(1000000), geoRadiusArgs);
geoResultList = geoResults.getContent();
for (GeoResult geoResult : geoResultList) {
System.out.println("geoRadiusByMember " + geoResult.getContent());
}
//删除位置信息,此命令不是geo提供的,是使用zrem命令删除的
System.out.println(boundGeoOperations.geoRemove("南京市"));
}
输出结果:
1
1
南京市到北京市之间的距离是:899.2222km
南京市的geoHash = wtsqrkqk120
南京市的经纬度为 = Point [x=118.803805, y=32.060168]
geoRadius RedisGeoCommands.GeoLocation(name=南京市, point=Point [x=118.803805, y=32.060168])
geoRadius RedisGeoCommands.GeoLocation(name=北京市, point=Point [x=116.397038, y=39.907701])
geoRadiusByMember RedisGeoCommands.GeoLocation(name=南京市, point=Point [x=118.803805, y=32.060168])
1
</div>