使用 RedisTemplate 进行相同的操作,示例代码如下:
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
public class GeoAddExample {
private RedisTemplate<String, String> redisTemplate;
public GeoAddExample(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void geoAdd() {
double longitude = 120.2179600;
double latitude = 30.2479600;
String member = "BT106003012MT00210932511";
Point point = new Point(longitude, latitude);
RedisGeoCommands.GeoLocation<String> location = new RedisGeoCommands.GeoLocation<>(member, point);
redisTemplate.opsForGeo().add("cabinet:battery:geo", location);
}
}
在这个示例中,我们使用 Spring Data Redis 提供的 RedisTemplate 类来连接到 Redis 服务器,并通过 opsForGeo() 方法获取操作有序集合的接口。然后,我们创建一个 Point 对象表示经纬度坐标,将其与成员一起封装在 GeoLocation 对象中,最后使用 add() 方法将其添加到指定的有序集合中。
请确保已正确配置和初始化了 RedisTemplate 实例,并将其作为构造函数参数传递给 GeoAddExample 类。
内容由零声教学AI助手提供,问题来源于学员提问




