RedisTemplate GEO使用
时间: 2023-07-11 18:12:41 浏览: 81
RedisTemplate 用法
RedisTemplate可以用于执行GEO命令,GEO是Redis提供的一种地理位置信息处理方式。以下是RedisTemplate GEO命令的使用示例:
1. 添加地理位置信息
```java
RedisGeoCommands.GeoLocation<String> location1 = new RedisGeoCommands.GeoLocation<>("Shanghai", new Point(121.47, 31.23));
RedisGeoCommands.GeoLocation<String> location2 = new RedisGeoCommands.GeoLocation<>("Beijing", new Point(116.40, 39.90));
RedisGeoCommands.GeoLocation<String> location3 = new RedisGeoCommands.GeoLocation<>("Guangzhou", new Point(113.23, 23.16));
List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>();
locations.add(location1);
locations.add(location2);
locations.add(location3);
redisTemplate.opsForGeo().add("china", locations);
```
2. 获取地理位置信息
```java
Distance distance = redisTemplate.opsForGeo().distance("china", "Shanghai", "Beijing", RedisGeoCommands.DistanceUnit.KILOMETERS);
System.out.println(distance.getValue() + distance.getUnit());
```
3. 查询指定范围内的地理位置信息
```java
Circle circle = new Circle(new Point(116.40, 39.90), new Distance(500, RedisGeoCommands.DistanceUnit.KILOMETERS));
GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius("china", circle);
for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : results) {
System.out.println(result.getContent().getName() + " " + result.getDistance().getValue() + result.getDistance().getUnit());
}
```
4. 查询指定地理位置与其他地理位置的距离
```java
Distance distance = redisTemplate.opsForGeo().distance("china", "Shanghai", "Guangzhou", RedisGeoCommands.DistanceUnit.KILOMETERS);
System.out.println(distance.getValue() + distance.getUnit());
```
5. 查询指定地理位置的经纬度坐标
```java
List<Point> points = redisTemplate.opsForGeo().position("china", "Beijing", "Shanghai", "Guangzhou");
for (Point point : points) {
System.out.println(point.getX() + "," + point.getY());
}
```
希望这些示例可以帮助你更好地使用RedisTemplate执行GEO命令。
阅读全文