Redis —— SpringBoot工程下的GeoHash工具类

一、依赖引入

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--redis连接依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

二、工具类代码

@Component
@Slf4j
public class RedisUtil {

    @Value("${spring.redis.geo.key}")
    private String GEO_REDIS_KEY;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 指定缓存失效时间
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("set expire time error.key:{}.", key, e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("redis hasKey method error.key:{}.", key, e);
            return false;
        }
    }

    /**
     * 删除缓存
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(Arrays.asList(key));
            }
        }
    }

    //------------------------------------GEO----------------------------------------

    /**
     * 增加用户位置
     */
    public Long addGeoLocation(String username, double x, double y) {
        try {
            RedisGeoCommands.GeoLocation geoLocation = new RedisGeoCommands.GeoLocation(username, new Point(x, y));
            return redisTemplate.opsForGeo().add(GEO_REDIS_KEY, geoLocation);
        } catch (Exception exception) {
            throw new RuntimeException("addGeoLocation error.", exception);
        }
    }

    /**
     * 删除用户位置,GEO实际上放在ZSET结构的数据,因此可用ZREM删除
     */
    public Long deleteGeoLocation(String username) {
        try {
            return redisTemplate.opsForZSet().remove(GEO_REDIS_KEY, username);
        } catch (Exception exception) {
            throw new RuntimeException("deleteGeoLocation error.", exception);
        }
    }

    /**
     * 获取用户位置
     */
    public List<Point> getGeoLocation(String username) {
        try {
            return redisTemplate.opsForGeo().position(GEO_REDIS_KEY, username);
        } catch (Exception e) {
            throw new RuntimeException("getGetLocation error.", e);
        }
    }

    /**
     * 计算用户相隔距离
     */
    public Distance getDistance(String usernameOne, String usernameTwo, RedisGeoCommands.DistanceUnit unit) {
        try {
            return redisTemplate.opsForGeo().distance(GEO_REDIS_KEY, usernameOne, usernameTwo,unit);
        } catch (Exception e) {
            throw new RuntimeException("getDistance error.", e);
        }
    }

    /**
     * 获取某个用户 附近 n个距离单位m 内的附近z个用户
     */
    public GeoResults<RedisGeoCommands.GeoLocation<Object>> getRadius(String username, int radius
            , RedisGeoCommands.DistanceUnit unit, int limit) {
        try {
            Distance distance = new Distance(radius, unit);
            RedisGeoCommands.GeoRadiusCommandArgs args =
                    RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates().sortAscending().limit(limit);
            return redisTemplate.opsForGeo().radius(GEO_REDIS_KEY, username, distance, args);
        } catch (Exception e) {
            throw new RuntimeException("getDistance error.", e);
        }
    }
}

三、使用样例

添加Redis相关yml配置。

# redis配置,以下有默认配置的也可以使用默认配置
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 123456    # 如果无密码,直接注释掉即可
    timeout: 1000
    pool:
      minIdle: 5
      maxIdle: 10
      maxWait: -1
      maxActive: 20
    geo:
      key: spring_homework
  application:
    name: position-provider

工具类相关Bean。

// ----------------------UserPosition------------------------------
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserPosition implements Serializable {
    private String username;    // 用户名
    private double longitude;   // 经度
    private double latitude;    // 纬度
}

// -----------------------UserNearby-----------------------------
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.geo.Distance;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserNearby implements Serializable {
    private Distance distance;
    private UserPosition position;
}

Service层使用RedisUtil。

@Slf4j
public class PositionServiceImpl implements PositionService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public List<UserPosition> getGeoLocation(String username) {
        log.info("username:{} delete geoLocation.",username);
        List<Point> points = redisUtil.getGeoLocation(username);
        List<UserPosition> positions = new ArrayList<>();
        for (Point point : points) {
            if (Objects.nonNull(point)) {
                positions.add(new UserPosition(username,point.getX(),point.getY()));
            }
        }
        return positions;
    }

    @Override
    public Long addGeoLocation(String username, double x, double y) {
        return redisUtil.addGeoLocation(username, x, y);
    }

    @Override
    public Long deleteGeoLocation(String username) {
        log.info("username:{} delete geoLocation.",username);
        return redisUtil.deleteGeoLocation(username);
    }

    @Override
    public Distance getDistance(String usernameOne, String usernameTwo, RedisGeoCommands.DistanceUnit unit) {
        return redisUtil.getDistance(usernameOne, usernameTwo, unit);
    }

    @Override
    public List<UserNearby> getRadius(String username, int radius, RedisGeoCommands.DistanceUnit unit, int limit) {
        GeoResults<RedisGeoCommands.GeoLocation<Object>> result = redisUtil.getRadius(username, radius, unit, limit);
        List<UserNearby> userNearbyList = new ArrayList<>();
        result.getContent().forEach((one) -> {
            userNearbyList.add(
                    new UserNearby(one.getDistance()
                                        , new UserPosition((String) one.getContent().getName(),one.getContent().getPoint().getX(),one.getContent().getPoint().getY()))
            );
        });
        return userNearbyList;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值