目录
-
org.springframework.boot -
spring-boot-starter-data-redis
- spring.redis.host=127.0.0.1
- #Redis服务器连接端口
- spring.redis.port=6379
- #Redis服务器连接密码(默认为空)
- spring.redis.password=
- #连接超时时间(毫秒)
- spring.redis.timeout=30000
- package com.zsp.quartz.service.impl;
-
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.geo.Circle;
- import org.springframework.data.geo.Distance;
- import org.springframework.data.geo.GeoResults;
- import org.springframework.data.geo.Point;
- import org.springframework.data.redis.connection.RedisGeoCommands;
- import org.springframework.data.redis.core.GeoOperations;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.core.ValueOperations;
- import org.springframework.stereotype.Service;
- import java.util.concurrent.TimeUnit;
-
- @Service
- public class RedisService {
-
- @Autowired
- private RedisTemplate
redisTemplate; -
- // 存入redis
- public void setValue(String key, String value) {
- ValueOperations
valueOperations = redisTemplate.opsForValue(); - valueOperations.set(key, value);
- }
- // 从redis取值
- public String getValue(String key) {
- ValueOperations
valueOperations = redisTemplate.opsForValue(); - return valueOperations.get(key);
- }
- // 存入redis带过期时间
- public void setValue(String key, String value, long expirationTimeInSeconds) {
- ValueOperations
valueOperations = redisTemplate.opsForValue(); - valueOperations.set(key, value, expirationTimeInSeconds, TimeUnit.SECONDS);
- }
-
- /**
- * 添加地理位置信息,附加名字
- * @param key 存入redis的key
- * @param longitude 经度
- * @param latitude 纬度
- * @param member 附加值 这里附加了名字
- */
- public void addLocation(String key, double longitude, double latitude, String member) {
- Point point = new Point(longitude, latitude);
- GeoOperations
geoOps = redisTemplate.opsForGeo(); - geoOps.add(key, point, member);
- }
-
- /**
- * 获取地理位置信息
- * @param key 存入redis的key
- * @param longitude 中心点经度
- * @param latitude 中心点纬度
- * @param radius 筛选半径
- * @return
- */
- public GeoResults
> getLocationsInRadius(String key, double longitude, double latitude, double radius) { - Point point = new Point(longitude, latitude);
- Distance distance = new Distance(radius);
- Circle circle = new Circle(point, distance);
- GeoOperations
geoOps = redisTemplate.opsForGeo(); - return geoOps.radius(key, circle);
- }
- }
- @Autowired
- RedisService redisService;
- @Test
- void testForGeo(){
- redisService.addLocation("locations", 13.361389, 38.115556, "Paris");
- redisService.addLocation("locations", 13.4125, 39.523333, "Berlin");
- redisService.addLocation("locations", -0.127758, 51.507351, "London");
-
- GeoResults
> locations = redisService.getLocationsInRadius("locations", 13.361389, 38.115556, 500000); - for (GeoResult
> location : locations) { - System.out.println(location.getContent().getName());
- }
- }
筛选半径单位:米,先存进去,再根据key和筛选半径取出符合条件的数据