Spring Boot实战分页查询附近的人: Redis+GeoHash+Lua

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Spring Boot实战分页查询附近的人: Redis+GeoHash+Lua

强烈推荐一个大神的人工智能的教程:http://www.captainai.net/zhanghan


前言


最近在做社交的业务,用户进入首页后需要查询附近的人;

项目状况:前期尝试业务阶段;


特点:

  • 快速实现(不需要做太重,满足初期推广运营即可)
  • 快速投入市场去运营


收集用户的经纬度:

  • 用户在每次启动时将当前的地理位置(经度,维度)上报给后台


提到附近的人,脑海中首先浮现特点:

  • 需要记录每位用户的经纬度
  • 查询当前用户附近的人,搜索在N公里内用户


架构设计


  • 时序图

a73d92eab85c6cb85b23883ce994d8be_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70#pic_center.png


  • 技术实现方案


SpringBoot


Redis(version>=3.2)


Redis原生命令实现


  • 存入用户的经纬度


  • geoadd 用于存储指定的地理空间位置,可以将一个或多个经度(longitude)、纬度(latitude)、位置名称(member)添加到指定的 key 中


  • 命令格式:


GEOADD key longitude latitude member [longitude latitude member ...]


  • 模拟五个用户存入经纬度,redis客户端执行如下命令:


GEOADD zhgeo 116.48105 39.996794 zhangsan
GEOADD zhgeo 116.514203 39.905409 lisi
GEOADD zhgeo 116.489033 40.007669 wangwu
GEOADD zhgeo 116.562108 39.787602 sunliu
GEOADD zhgeo 116.334255 40.027400 zhaoqi


  • 通过redis客户端查看效果:

20200809180623685.png


  • 查找距当前用户由近到远附近100km用户


  • georadiusbymember可以找出位于指定范围内的元素,georadiusbymember 的中心点是由给定的位置元素决定的
  • 命令格式:
GEORADIUSBYMEMBER key member radius m|km|ft|mi [WITHCOORD] [WITHDIST] [WITHHASH] [COUNT count] [ASC|DESC] [STORE key] [STOREDIST key]


  • 模拟查找100km里距离sunliu由近到远五个人
georadiusbymember zhgeo sunliu 100 km asc count 5


  • 命令执行效果如下:

20200809180856647.png


  • 如何实现分页查询那?


  • 每次分页查询的请求都计算一次然后拿到程序中在取相应的分页数据,优缺点:


  • 优点:实现简单,无需额外的存储空间
  • 缺点:当用户量大时,很显然不仅效率低,而且容易把程序的内存搞溢出
  • 经过查找发现redis的github官网给出了分页Issues(参考:Will the GEORADIUS support pagination?),解决方案如下:


  • 利用GEORADIUSBYMEMBER 命令中的 STOREDIST 将排好序的数据存入一个Zset集合中,以后分页查直接从Zset


  • 命令如下:


georadiusbymember zhgeo sunliu 100 km asc count 5 storedist sunliu


  • 有序集合效果如下:

20200809180939803.png


  • 以后分页查询命令:


//首先删除本身元素
zrem sunliu sunliu
//分页查找元素(在此以:查找第1页,每页数量是3为例)
zrange sunliu 0 2 withscores


  • 效果如下:


20200809181007105.png


代码实现


  • 完整代码(GitHub,欢迎大家Star,Fork,Watch)


https://github.com/dangnianchuntian/springboot


  • 主要代码展示


  • Controller
/*
 * Copyright (c) 2020. zhanghan_java@163.com All Rights Reserved.
 * 项目名称:Spring Boot实战分页查询附近的人: Redis+GeoHash+Lua
 * 类名称:GeoController.java
 * 创建人:张晗
 * 联系方式:zhanghan_java@163.com
 * 开源地址: https://github.com/dangnianchuntian/springboot
 * 博客地址: https://zhanghan.blog.csdn.net
 */
package com.zhanghan.zhnearbypeople.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.zhanghan.zhnearbypeople.controller.request.ListNearByPeopleRequest;
import com.zhanghan.zhnearbypeople.controller.request.PostGeoRequest;
import com.zhanghan.zhnearbypeople.service.GeoService;
@RestController
public class GeoController {
    @Autowired
    private GeoService geoService;
    /**
     * 记录用户地理位置
     */
    @RequestMapping(value = "/post/geo", method = RequestMethod.POST)
    public Object postGeo(@RequestBody @Validated PostGeoRequest postGeoRequest) {
        return geoService.postGeo(postGeoRequest);
    }
    /**
     * 分页查询当前用户附近的人
     */
    @RequestMapping(value = "/list/nearby/people", method = RequestMethod.POST)
    public Object listNearByPeople(@RequestBody @Validated ListNearByPeopleRequest listNearByPeopleRequest) {
        return geoService.listNearByPeople(listNearByPeopleRequest);
    }
}


  • service


/*
 * Copyright (c) 2020. zhanghan_java@163.com All Rights Reserved.
 * 项目名称:Spring Boot实战分页查询附近的人: Redis+GeoHash+Lua
 * 类名称:GeoServiceImpl.java
 * 创建人:张晗
 * 联系方式:zhanghan_java@163.com
 * 开源地址: https://github.com/dangnianchuntian/springboot
 * 博客地址: https://zhanghan.blog.csdn.net
 */
package com.zhanghan.zhnearbypeople.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import com.zhanghan.zhnearbypeople.controller.request.ListNearByPeopleRequest;
import com.zhanghan.zhnearbypeople.controller.request.PostGeoRequest;
import com.zhanghan.zhnearbypeople.dto.NearByPeopleDto;
import com.zhanghan.zhnearbypeople.service.GeoService;
import com.zhanghan.zhnearbypeople.util.RedisLuaUtil;
import com.zhanghan.zhnearbypeople.util.wrapper.WrapMapper;
@Service
public class GeoServiceImpl implements GeoService {
    private static Logger logger = LoggerFactory.getLogger(GeoServiceImpl.class);
    @Autowired
    private RedisTemplate<String, Object> objRedisTemplate;
    @Value("${zh.geo.redis.key:zhgeo}")
    private String zhGeoRedisKey;
    @Value("${zh.geo.zset.redis.key:zhgeozset:}")
    private String zhGeoZsetRedisKey;
    /**
     * 记录用户访问记录
     */
    @Override
    public Object postGeo(PostGeoRequest postGeoRequest) {
        //对应redis原生命令:GEOADD zhgeo 116.48105 39.996794 zhangsan
        Long flag = objRedisTemplate.opsForGeo().add(zhGeoRedisKey, new RedisGeoCommands.GeoLocation<>(postGeoRequest
                .getCustomerId(), new Point(postGeoRequest.getLatitude(), postGeoRequest.getLongitude())));
        if (null != flag && flag > 0) {
            return WrapMapper.ok();
        }
        return WrapMapper.error();
    }
    /**
     * 分页查询附近的人
     */
    @Override
    public Object listNearByPeople(ListNearByPeopleRequest listNearByPeopleRequest) {
        String customerId = listNearByPeopleRequest.getCustomerId();
        String strZsetUserKey = zhGeoZsetRedisKey + customerId;
        List<NearByPeopleDto> nearByPeopleDtoList = new ArrayList<>();
        //如果是从第1页开始查,则将附近的人写入zset集合,以后页直接从zset中查
        if (1 == listNearByPeopleRequest.getPageIndex()) {
            List<String> scriptParams = new ArrayList<>();
            scriptParams.add(zhGeoRedisKey);
            scriptParams.add(customerId);
            scriptParams.add("100");
            scriptParams.add(RedisGeoCommands.DistanceUnit.KILOMETERS.getAbbreviation());
            scriptParams.add("asc");
            scriptParams.add("storedist");
            scriptParams.add(strZsetUserKey);
            //用Lua脚本实现georadiusbymember中的storedist参数
            //对应Redis原生命令:georadiusbymember zhgeo sunliu 100 km asc count 5 storedist sunliu
            Long executeResult = objRedisTemplate.execute(RedisLuaUtil.GEO_RADIUS_STOREDIST_SCRIPT(), scriptParams);
            if (null == executeResult || executeResult < 1) {
                return WrapMapper.ok(nearByPeopleDtoList);
            }
            //zset集合中去除自己
            //对应Redis原生命令:zrem sunliu sunliu
            Long remove = objRedisTemplate.opsForZSet().remove(strZsetUserKey, customerId);
        }
        nearByPeopleDtoList = listNearByPeopleFromZset(strZsetUserKey, listNearByPeopleRequest.getPageIndex(),
                listNearByPeopleRequest.getPageSize());
        return WrapMapper.ok(nearByPeopleDtoList);
    }
    /**
     * 分页从zset中查询指定用户附近的人
     */
    private List<NearByPeopleDto> listNearByPeopleFromZset(String strZsetUserKey, Integer pageIndex, Integer pageSize) {
        Integer startPage = (pageIndex - 1) * pageSize;
        Integer endPage = pageIndex * pageSize - 1;
        List<NearByPeopleDto> nearByPeopleDtoList = new ArrayList<>();
        //对应Redis原生命令:zrange key 0 2 withscores
        Set<ZSetOperations.TypedTuple<Object>> zsetUsers = objRedisTemplate.opsForZSet()
                .rangeWithScores(strZsetUserKey, startPage,
                        endPage);
        for (ZSetOperations.TypedTuple<Object> zsetUser : zsetUsers) {
            NearByPeopleDto nearByPeopleDto = new NearByPeopleDto();
            nearByPeopleDto.setCustomerId(zsetUser.getValue().toString());
            nearByPeopleDto.setDistance(zsetUser.getScore());
            nearByPeopleDtoList.add(nearByPeopleDto);
        }
        return nearByPeopleDtoList;
    }
}
  • RedisLuaUtil


/*
 * Copyright (c) 2020. zhanghan_java@163.com All Rights Reserved.
 * 项目名称:Spring Boot实战分页查询附近的人: Redis+GeoHash+Lua
 * 类名称:RedisLuaUtil.java
 * 创建人:张晗
 * 联系方式:zhanghan_java@163.com
 * 开源地址: https://github.com/dangnianchuntian/springboot
 * 博客地址: https://zhanghan.blog.csdn.net
 */
package com.zhanghan.zhnearbypeople.util;
import org.springframework.data.redis.core.script.DigestUtils;
import org.springframework.data.redis.core.script.RedisScript;
public class RedisLuaUtil {
    private static final RedisScript<Long> GEO_RADIUS_STOREDIST_SCRIPT;
    public static RedisScript<Long> GEO_RADIUS_STOREDIST_SCRIPT() {
        return GEO_RADIUS_STOREDIST_SCRIPT;
    }
    static {
        StringBuilder sb = new StringBuilder();
        sb.append("return redis.call('georadiusbymember',KEYS[1],KEYS[2],KEYS[3],KEYS[4],KEYS[5],KEYS[6],KEYS[7])");
        GEO_RADIUS_STOREDIST_SCRIPT = new RedisScriptImpl<>(sb.toString(), Long.class);
    }
    private static class RedisScriptImpl<T> implements RedisScript<T> {
        private final String script;
        private final String sha1;
        private final Class<T> resultType;
        public RedisScriptImpl(String script, Class<T> resultType) {
            this.script = script;
            this.sha1 = DigestUtils.sha1DigestAsHex(script);
            this.resultType = resultType;
        }
        @Override
        public String getSha1() {
            return sha1;
        }
        @Override
        public Class<T> getResultType() {
            return resultType;
        }
        @Override
        public String getScriptAsString() {
            return script;
        }
    }
}


测试


  • 模拟用户上传地理位置进行存储


  • 进行请求

6197184373c2042503b76aec8f0917ad_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70#pic_center.png


  • 查看效果

20200809181457887.png

2020080918155012.png

  • 模拟用户sunliu查找附近100km的人,按3条一分页进行查询
  • 进行请求

7e26db4ad1a2ed548f34b0205c7566bd_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70#pic_center.png


总结


  • 亮点:
  • 分页实现思路:将geo集合中的数据按距离由近到远筛选好后,通过storedist放入一个新的Zset集合
  • redisTemplate没有针对原生命令georadiusbymember的storedist参数实现,灵活运用Lua脚本去实现
  • geo集合在亿级别以内的数据量没有问题,当超过亿后需要根据产品需要对Redis中的大值进行拆分,比如按照地域进行拆分等
  • 有了地理位置,自己正在研究如何通过经纬度绘制出自己的运动路线,验证出来后与大家共享

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
25 3
|
1天前
|
安全 Java 开发者
深入理解Spring Boot配置绑定及其实战应用
【4月更文挑战第10天】本文详细探讨了Spring Boot中配置绑定的核心概念,并结合实战示例,展示了如何在项目中有效地使用这些技术来管理和绑定配置属性。
13 1
|
1天前
|
安全 Java 测试技术
Spring Boot集成支付宝支付:概念与实战
【4月更文挑战第29天】在电子商务和在线业务应用中,集成有效且安全的支付解决方案是至关重要的。支付宝作为中国领先的支付服务提供商,其支付功能的集成可以显著提升用户体验。本篇博客将详细介绍如何在Spring Boot应用中集成支付宝支付功能,并提供一个实战示例。
37 2
|
1天前
|
开发框架 监控 Java
深入探索Spring Boot的监控、管理和测试功能及实战应用
【5月更文挑战第14天】Spring Boot是一个快速开发框架,提供了一系列的功能模块,包括监控、管理和测试等。本文将深入探讨Spring Boot中监控、管理和测试功能的原理与应用,并提供实际应用场景的示例。
14 2
|
1天前
|
存储 NoSQL Redis
Redis数据结构精讲:选择与应用实战指南
Redis数据结构精讲:选择与应用实战指南
14 0
|
1天前
|
JSON NoSQL Java
深入浅出Redis(十三):SpringBoot整合Redis客户端
深入浅出Redis(十三):SpringBoot整合Redis客户端
|
1天前
|
存储 缓存 NoSQL
深入浅出Redis(十):Redis的Lua脚本
深入浅出Redis(十):Redis的Lua脚本
|
1天前
|
Java Spring 容器
深入理解Spring Boot启动流程及其实战应用
【5月更文挑战第9天】本文详细解析了Spring Boot启动流程的概念和关键步骤,并结合实战示例,展示了如何在实际开发中运用这些知识。
18 2
|
1天前
|
JavaScript Java 开发者
Spring Boot中的@Lazy注解:概念及实战应用
【4月更文挑战第7天】在Spring Framework中,@Lazy注解是一个非常有用的特性,它允许开发者控制Spring容器的bean初始化时机。本文将详细介绍@Lazy注解的概念,并通过一个实际的例子展示如何在Spring Boot应用中使用它。
21 2
|
1天前
|
监控 NoSQL 算法
探秘Redis分布式锁:实战与注意事项
本文介绍了Redis分区容错中的分布式锁概念,包括利用Watch实现乐观锁和使用setnx防止库存超卖。乐观锁通过Watch命令监控键值变化,在事务中执行修改,若键值被改变则事务失败。Java代码示例展示了具体实现。setnx命令用于库存操作,确保无超卖,通过设置锁并检查库存来更新。文章还讨论了分布式锁存在的问题,如客户端阻塞、时钟漂移和单点故障,并提出了RedLock算法来提高可靠性。Redisson作为生产环境的分布式锁实现,提供了可重入锁、读写锁等高级功能。最后,文章对比了Redis、Zookeeper和etcd的分布式锁特性。
129 16
探秘Redis分布式锁:实战与注意事项
http://www.vxiaotou.com