redis geo RedisTemplate工具类
时间: 2023-12-31 18:04:48 浏览: 129
RedisTemplate是Spring框架提供的一个Redis操作工具类,封装了Redis连接池的操作。在使用Redis的时候,可以通过RedisTemplate对Redis进行操作,包括String、Hash、List、Set、ZSet、HyperLogLog等数据结构的操作。
在使用RedisTemplate进行geo操作时,需要先设置序列化方式为GenericJackson2JsonRedisSerializer,然后通过GeoOperations接口进行操作。GeoOperations包括添加地理位置信息、获取两个位置之间的距离、获取指定位置的附近的其他位置信息等操作。
以下是RedisTemplate工具类的示例代码:
```
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(lettuceConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
@Service
public class RedisGeoService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public Object addGeo(String key, GeoLocation<Object> location) {
GeoOperations<String, Object> geoOperations = redisTemplate.opsForGeo();
return geoOperations.add(key, location);
}
public Object getDistance(String key, Object member1, Object member2) {
GeoOperations<String, Object> geoOperations = redisTemplate.opsForGeo();
return geoOperations.distance(key, member1, member2);
}
public Object getRadius(String key, Object member, double radius, Metric metric) {
GeoOperations<String, Object> geoOperations = redisTemplate.opsForGeo();
return geoOperations.radius(key, member, new Distance(radius, metric));
}
}
```
阅读全文