当前位置: 代码网 > it编程>编程语言>Java > SpringBoot3.0 + Redis 实现附近的人功能

SpringBoot3.0 + Redis 实现附近的人功能

2026年11月29日 • Java •我要评论
一、原理概述redis 3.2+ 版本提供了 geo(地理位置) 数据结构,专门用于存储和查询地理位置信息。核心命令包括:命令功能geoadd添加地理位置georadius/geosearch搜索指定

一、原理概述

redis 3.2+ 版本提供了 geo(地理位置) 数据结构,专门用于存储和查询地理位置信息。核心命令包括:

命令功能
geoadd添加地理位置
georadius / geosearch搜索指定范围内的成员
geodist计算两点距离
geopos获取成员坐标

二、项目搭建

1. 创建 spring boot 3.0 项目

pom.xml 依赖:

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://maven.apache.org/pom/4.0.0 
         https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelversion>4.0.0</modelversion>
    <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>3.0.0</version>
        <relativepath/>
    </parent>
    <groupid>com.example</groupid>
    <artifactid>redis-nearby</artifactid>
    <version>1.0.0</version>
    <name>redis-nearby</name>
    <description>redis 附近的人功能</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <!-- spring boot web -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>
        <!-- spring data redis -->
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-redis</artifactid>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupid>org.projectlombok</groupid>
            <artifactid>lombok</artifactid>
            <optional>true</optional>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupid>org.apache.commons</groupid>
            <artifactid>commons-pool2</artifactid>
        </dependency>
    </dependencies>
</project>

2. 配置文件

application.yml:

spring:
  data:
    redis:
      host: localhost
      port: 6379
      password:       # 如果有密码请填写
      database: 0
      lettuce:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0
          max-wait: -1ms
# 自定义配置
nearby:
  redis-key: "user:location"  # redis中存储位置的key
  default-radius: 5000        # 默认搜索半径:5公里(单位:米)
  max-radius: 50000           # 最大搜索半径:50公里

三、核心代码实现

1. 实体类

package com.example.redisnearby.entity;
import lombok.allargsconstructor;
import lombok.builder;
import lombok.data;
import lombok.noargsconstructor;
/**
 * 用户位置信息
 */
@data
@builder
@noargsconstructor
@allargsconstructor
public class userlocation {
    /** 用户id */
    private string userid;
    /** 经度 */
    private double longitude;
    /** 纬度 */
    private double latitude;
    /** 用户名/昵称 */
    private string username;
    /** 头像url */
    private string avatar;
    /** 更新时间戳 */
    private long updatetime;
}
package com.example.redisnearby.dto;
import lombok.allargsconstructor;
import lombok.builder;
import lombok.data;
import lombok.noargsconstructor;
/**
 * 附近的人dto
 */
@data
@builder
@noargsconstructor
@allargsconstructor
public class nearbyuserdto {
    /** 用户id */
    private string userid;
    /** 用户名 */
    private string username;
    /** 头像 */
    private string avatar;
    /** 距离(米) */
    private double distance;
    /** 经度 */
    private double longitude;
    /** 纬度 */
    private double latitude;
}

2. redis配置类

package com.example.redisnearby.config;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.redis.connection.redisconnectionfactory;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.data.redis.serializer.genericjackson2jsonredisserializer;
import org.springframework.data.redis.serializer.stringredisserializer;
@configuration
public class redisconfig {
    @bean
    public redistemplate<string, object> redistemplate(redisconnectionfactory connectionfactory) {
        redistemplate<string, object> template = new redistemplate<>();
        template.setconnectionfactory(connectionfactory);
        // key序列化
        template.setkeyserializer(new stringredisserializer());
        template.sethashkeyserializer(new stringredisserializer());
        // value序列化
        template.setvalueserializer(new genericjackson2jsonredisserializer());
        template.sethashvalueserializer(new genericjackson2jsonredisserializer());
        template.afterpropertiesset();
        return template;
    }
}

3. 核心service层

package com.example.redisnearby.service;
import com.example.redisnearby.dto.nearbyuserdto;
import com.example.redisnearby.entity.userlocation;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.value;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.redisgeocommands;
import org.springframework.data.redis.core.redistemplate;
import org.springframework.stereotype.service;
import java.util.arraylist;
import java.util.list;
import java.util.concurrent.timeunit;
@slf4j
@service
@requiredargsconstructor
public class nearbyservice {
    private final redistemplate<string, object> redistemplate;
    @value("${nearby.redis-key}")
    private string locationkey;
    @value("${nearby.default-radius}")
    private double defaultradius;
    @value("${nearby.max-radius}")
    private double maxradius;
    /**
     * 更新用户位置(上报位置)
     *
     * @param userlocation 用户位置信息
     */
    public void updatelocation(userlocation userlocation) {
        // 参数校验
        if (userlocation.getlongitude() == null || userlocation.getlatitude() == null) {
            throw new illegalargumentexception("经纬度不能为空");
        }
        // 校验经纬度范围
        if (userlocation.getlongitude() < -180 || userlocation.getlongitude() > 180 ||
            userlocation.getlatitude() < -90 || userlocation.getlatitude() > 90) {
            throw new illegalargumentexception("经纬度范围不合法");
        }
        // 使用 geoadd 命令添加位置
        // redis 内部使用 sorted set 存储,score 是经纬度编码后的值
        long added = redistemplate.opsforgeo().add(
            locationkey,
            new point(userlocation.getlongitude(), userlocation.getlatitude()),
            userlocation.getuserid()
        );
        // 可选:存储用户额外信息(用户名、头像等)
        string userinfokey = "user:info:" + userlocation.getuserid();
        redistemplate.opsforhash().put(userinfokey, "username", userlocation.getusername());
        redistemplate.opsforhash().put(userinfokey, "avatar", userlocation.getavatar());
        redistemplate.opsforhash().put(userinfokey, "updatetime", system.currenttimemillis());
        // 设置过期时间(例如7天未更新则删除)
        redistemplate.expire(userinfokey, 7, timeunit.days);
        redistemplate.expire(locationkey, 7, timeunit.days);
        log.info("用户 [{}] 更新位置成功: ({}, {})", 
            userlocation.getuserid(), 
            userlocation.getlongitude(), 
            userlocation.getlatitude()
        );
    }
    /**
     * 搜索附近的人(圆形范围)
     *
     * @param longitude 中心点经度
     * @param latitude  中心点纬度
     * @param radius    半径(米)
     * @param limit     返回数量限制
     * @return 附近用户列表
     */
    public list<nearbyuserdto> findnearbyusers(double longitude, double latitude, 
                                                double radius, integer limit) {
        // 参数校验和默认值处理
        if (radius == null || radius <= 0) {
            radius = defaultradius;
        }
        // 限制最大搜索范围,防止性能问题
        radius = math.min(radius, maxradius);
        if (limit == null || limit <= 0) {
            limit = 20; // 默认返回20个
        }
        // 构建圆心和距离
        circle circle = new circle(
            new point(longitude, latitude),
            new distance(radius, metrics.meters)
        );
        // 构建查询参数
        redisgeocommands.georadiuscommandargs args = redisgeocommands.georadiuscommandargs
            .newgeoradiusargs()
            .includedistance()  // 包含距离信息
            .includecoordinates() // 包含坐标信息
            .sortascending()    // 按距离升序
            .limit(limit);      // 限制数量
        // 执行 georadius 命令
        georesults<redisgeocommands.geolocation<object>> results = 
            redistemplate.opsforgeo().radius(locationkey, circle, args);
        list<nearbyuserdto> nearbyusers = new arraylist<>();
        if (results == null || results.getcontent().isempty()) {
            return nearbyusers;
        }
        // 处理结果
        for (georesult<redisgeocommands.geolocation<object>> result : results) {
            string userid = (string) result.getcontent().getname();
            point point = result.getcontent().getpoint();
            distance distance = result.getdistance();
            // 查询用户详细信息
            string userinfokey = "user:info:" + userid;
            string username = (string) redistemplate.opsforhash().get(userinfokey, "username");
            string avatar = (string) redistemplate.opsforhash().get(userinfokey, "avatar");
            nearbyuserdto dto = nearbyuserdto.builder()
                .userid(userid)
                .username(username != null ? username : "用户" + userid)
                .avatar(avatar)
                .distance(distance.getvalue()) // 距离(米)
                .longitude(point.getx())
                .latitude(point.gety())
                .build();
            nearbyusers.add(dto);
        }
        return nearbyusers;
    }
    /**
     * 搜索附近的人(使用 geosearch,redis 6.2+ 推荐)
     * 功能更强大,支持按成员搜索
     */
    public list<nearbyuserdto> findnearbyusersbymember(string userid, double radius, integer limit) {
        // 限制范围
        if (radius == null || radius <= 0) {
            radius = defaultradius;
        }
        radius = math.min(radius, maxradius);
        if (limit == null || limit <= 0) {
            limit = 20;
        }
        // 使用 geosearch 命令(需要 redis 6.2+)
        // 注意:spring data redis 可能需要使用 execute 方法直接执行命令
        distance distance = new distance(radius, metrics.meters);
        // 构建参数
        redisgeocommands.georadiuscommandargs args = redisgeocommands.georadiuscommandargs
            .newgeoradiusargs()
            .includedistance()
            .includecoordinates()
            .sortascending()
            .limit(limit);
        // 以指定用户为中心搜索
        georesults<redisgeocommands.geolocation<object>> results = 
            redistemplate.opsforgeo().radius(
                locationkey, 
                userid, 
                distance, 
                args
            );
        return converttodto(results);
    }
    /**
     * 计算两个用户之间的距离
     */
    public double getdistance(string userid1, string userid2) {
        distance distance = redistemplate.opsforgeo()
            .distance(locationkey, userid1, userid2, metrics.meters);
        return distance != null ? distance.getvalue() : null;
    }
    /**
     * 删除用户位置
     */
    public void removelocation(string userid) {
        redistemplate.opsforgeo().remove(locationkey, userid);
        redistemplate.delete("user:info:" + userid);
        log.info("删除用户 [{}] 的位置信息", userid);
    }
    /**
     * 获取用户当前位置
     */
    public point getuserlocation(string userid) {
        list<point> points = redistemplate.opsforgeo().position(locationkey, userid);
        return (points != null && !points.isempty()) ? points.get(0) : null;
    }
    // 辅助方法:转换结果
    private list<nearbyuserdto> converttodto(
        georesults<redisgeocommands.geolocation<object>> results) {
        list<nearbyuserdto> list = new arraylist<>();
        if (results == null) return list;
        for (georesult<redisgeocommands.geolocation<object>> result : results) {
            string userid = (string) result.getcontent().getname();
            point point = result.getcontent().getpoint();
            distance distance = result.getdistance();
            string userinfokey = "user:info:" + userid;
            string username = (string) redistemplate.opsforhash().get(userinfokey, "username");
            string avatar = (string) redistemplate.opsforhash().get(userinfokey, "avatar");
            list.add(nearbyuserdto.builder()
                .userid(userid)
                .username(username != null ? username : "用户" + userid)
                .avatar(avatar)
                .distance(distance.getvalue())
                .longitude(point.getx())
                .latitude(point.gety())
                .build());
        }
        return list;
    }
}

四、controller 接口层

package com.example.redisnearby.controller;
import com.example.redisnearby.dto.nearbyuserdto;
import com.example.redisnearby.entity.userlocation;
import com.example.redisnearby.service.nearbyservice;
import com.example.redisnearby.vo.result;
import lombok.requiredargsconstructor;
import org.springframework.web.bind.annotation.*;
import java.util.list;
@restcontroller
@requestmapping("/api/nearby")
@requiredargsconstructor
public class nearbycontroller {
    private final nearbyservice nearbyservice;
    /**
     * 上报/更新位置
     * post /api/nearby/location
     */
    @postmapping("/location")
    public result<void> updatelocation(@requestbody userlocation location) {
        nearbyservice.updatelocation(location);
        return result.success();
    }
    /**
     * 搜索附近的人
     * get /api/nearby/search?longitude=116.397&latitude=39.916&radius=5000&limit=20
     */
    @getmapping("/search")
    public result<list<nearbyuserdto>> searchnearby(
            @requestparam double longitude,
            @requestparam double latitude,
            @requestparam(required = false) double radius,
            @requestparam(required = false) integer limit) {
        list<nearbyuserdto> users = nearbyservice.findnearbyusers(longitude, latitude, radius, limit);
        return result.success(users);
    }
    /**
     * 获取与某用户的距离
     * get /api/nearby/distance?userid1=1001&userid2=1002
     */
    @getmapping("/distance")
    public result<double> getdistance(@requestparam string userid1, @requestparam string userid2) {
        double distance = nearbyservice.getdistance(userid1, userid2);
        return result.success(distance);
    }
    /**
     * 删除位置
     * delete /api/nearby/location/{userid}
     */
    @deletemapping("/location/{userid}")
    public result<void> removelocation(@pathvariable string userid) {
        nearbyservice.removelocation(userid);
        return result.success();
    }
}

统一返回结果类:

package com.example.redisnearby.vo;
import lombok.data;
@data
public class result<t> {
    private integer code;
    private string message;
    private t data;
    public static <t> result<t> success(t data) {
        result<t> result = new result<>();
        result.setcode(200);
        result.setmessage("success");
        result.setdata(data);
        return result;
    }
    public static <t> result<t> success() {
        return success(null);
    }
    public static <t> result<t> error(string message) {
        result<t> result = new result<>();
        result.setcode(500);
        result.setmessage(message);
        return result;
    }
}

五、测试用例

package com.example.redisnearby;
import com.example.redisnearby.dto.nearbyuserdto;
import com.example.redisnearby.entity.userlocation;
import com.example.redisnearby.service.nearbyservice;
import org.junit.jupiter.api.test;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import java.util.list;
@springboottest
class nearbyservicetest {
    @autowired
    private nearbyservice nearbyservice;
    @test
    void testnearby() {
        // 模拟添加一些用户位置(北京天安门附近)
        // 天安门坐标:116.397428, 39.90923
        // 用户1:在天安门
        nearbyservice.updatelocation(userlocation.builder()
            .userid("1001")
            .username("张三")
            .avatar("http://example.com/avatar1.jpg")
            .longitude(116.397428)
            .latitude(39.90923)
            .build());
        // 用户2:距离天安门 1公里
        nearbyservice.updatelocation(userlocation.builder()
            .userid("1002")
            .username("李四")
            .avatar("http://example.com/avatar2.jpg")
            .longitude(116.407428)
            .latitude(39.90923)
            .build());
        // 用户3:距离天安门 10公里
        nearbyservice.updatelocation(userlocation.builder()
            .userid("1003")
            .username("王五")
            .avatar("http://example.com/avatar3.jpg")
            .longitude(116.497428)
            .latitude(39.90923)
            .build());
        // 搜索附近5公里的人
        system.out.println("=== 搜索天安门附近5公里的人 ===");
        list<nearbyuserdto> nearbyusers = nearbyservice.findnearbyusers(
            116.397428, 39.90923, 5000.0, 10);
        nearbyusers.foreach(user -> {
            system.out.printf("用户: %s, 距离: %.2f米%n", 
                user.getusername(), user.getdistance());
        });
        // 计算两个用户距离
        double distance = nearbyservice.getdistance("1001", "1002");
        system.out.printf("%n1001和1002之间的距离: %.2f米%n", distance);
    }
}

六、redis 命令行验证

启动 redis 后,可以用以下命令验证数据:

# 查看所有位置成员
zrange user:location 0 -1 withscores
# 查看某个成员的坐标
geopos user:location 1001 1002
# 手动搜索附近的人
georadius user:location 116.397428 39.90923 5000 m withdist withcoord asc
# 查看用户详细信息
hgetall user:info:1001

七、性能优化建议

优化点方案
数据分片按城市或地理网格分片存储,避免单个key数据过大
定期清理设置 ttl 或定时任务清理不活跃用户信息
缓存用户信息使用本地缓存(caffeine)减少 redis 访问
限流对搜索接口 做限流,防止恶意刷接口
坐标精度根据业务需求,适当降低坐标精度(如保留6位小数)

八、项目结构

redis-nearby/
├── src/main/java/com/example/redisnearby/
│   ├── config/
│   │   └── redisconfig.java
│   ├── controller/
│   │   └── nearbycontroller.java
│   ├── dto/
│   │   └── nearbyuserdto.java
│   ├── entity/
│   │   └── userlocation.java
│   ├── service/
│   │   └── nearbyservice.java
│   ├── vo/
│   │   └── result.java
│   └── redisnearbyapplication.java
├── src/main/resources/
│   └── application.yml
└── pom.xml

九、总结

实现了基于 redis geo 的"附近的人"功能,核心优势:

  1. 高性能:redis 内存操作,毫秒级响应
  2. 简单易用:spring data redis 封装了复杂命令
  3. 功能完善:支持距离计算、范围搜索、排序等
  4. 扩展性强:可结合 geohash 实现更复杂的地理需求

到此这篇关于springboot3.0 + redis 实现“附近的人“功能的文章就介绍到这了,更多相关springboot redis 附近的人内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

赞 (0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com