Spring Boot 整合 Redis 实现附近位置查找 (LBS功能)

1. 引言

在很多场景中,如外卖、快递、打车等应用,我们需要实现"查找附近"的功能,以便根据用户的地理位置推荐附近的商家或服务。Redis 提供了 GEO 数据结构,可以高效地存储和查询地理位置数据。本文将介绍如何使用 Spring Boot + Redis 来实现附近位置查找。

Redis GEO 的核心优势

  • 高效存储:Redis 将地理空间数据存储为有序集合,优化了查询性能。
  • 灵活查询:GEORADIUS 等命令支持基于半径的搜索,并提供丰富的选项。
  • 高性能:内存存储确保低延迟,适合实时应用。

2. 技术选型

本项目主要使用的技术栈如下:

  • Spring Boot 3.0+ - 简化开发,提高效率
  • Spring Data Redis - 方便地操作 Redis
  • Redis GEO - 存储和查询地理位置数据
  • JUnit 5 - 进行单元测试

3. 环境准备

3.1 Redis 安装

确保你的 Redis 版本 >= 3.2,因为 GEO 命令是在 3.2 版本之后新增的。

css 复制代码
# 使用 Docker 启动 Redis
$ docker run -d --name redis -p 6379:6379 redis:latest

4. Spring Boot 配置 Redis

4.1 引入依赖

pom.xml 中添加 Redis 依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

4.2 配置 Redis 连接

application.yml 中配置 Redis 连接信息:

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

注意:

  • host 指定 Redis 服务器的地址,默认是 localhost
  • port 指定 Redis 的端口,默认 6379
  • lettuce 是 Redis 连接池配置,建议调整 max-active 来优化性能

5. 编写业务代码

5.1 定义 Store 门店实体

less 复制代码
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Store {
    private Long id;
    private String name;
    private double longitude;
    private double latitude;
    private String address;
}

说明:

  • longitudelatitude 存储经纬度
  • id 作为门店的唯一标识

5.2 编写 Redis GEO 相关操作

1. 添加门店数据到 Redis

typescript 复制代码
@Autowired
private RedisTemplate<String, String> redisTemplate;

private static final String GEO_KEY = "stores:geo";

public void addStore(Store store) {
    redisTemplate.opsForGeo().add(
        GEO_KEY,
        new Point(store.getLongitude(), store.getLatitude()),
        store.getId().toString()
    );
}

注意事项:

  • opsForGeo().add() 方法将门店数据存入 Redis
  • store.getLongitude()store.getLatitude() 确保正确传入
  • store.getId().toString() 作为 key,保证唯一性

2. 查询附近门店

scss 复制代码
public List<Store> findNearbyStores(double longitude, double latitude, double radiusKm) {
		// 创建该坐标需要查找的半径
    Circle circle = new Circle(new Point(longitude, latitude), new Distance(radiusKm, Metrics.KILOMETERS));

   // 创建所需结果集参数
    RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs()
            .includeDistance() //包含距离
            .includeCoordinates() //包含坐标
            .sortAscending() //升序排列
            .limit(10);  //结果集数量

    GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius(GEO_KEY, circle, args);

    List<Store> stores = new ArrayList<>();
    if (results != null) {
        for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : results) {
            String storeId = result.getContent().getName();
            Point point = result.getContent().getPoint();
            Distance distance = result.getDistance();
            stores.add(new Store(Long.parseLong(storeId), "", point.getX(), point.getY(), ""));
            System.out.println("Store ID: " + storeId + ", Distance: " + distance.getValue() + " km");
        }
    }
    return stores;
}

说明:

  • Circle 定义查询范围
  • includeDistance() 返回距离
  • includeCoordinates() 返回坐标
  • sortAscending() 按距离排序
  • limit(10) 限制返回 10 条数据

6. 编写单元测试

java 复制代码
@SpringBootTest
class CharmingApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String GEO_KEY = "stores:geo";

    @Test
    void testFindNearbyStores() {
        redisTemplate.delete(GEO_KEY);

        List<Store> testStores = List.of(
            new Store(100L, "Store A", 116.404, 39.915, "北京天安门"),
            new Store(200L, "Store B", 116.461, 39.923, "北京三里屯"),
            new Store(300L, "Store C", 116.355, 39.901, "北京西单")
        );

        for (Store store : testStores) {
            redisTemplate.opsForGeo().add(GEO_KEY, new Point(store.getLongitude(), store.getLatitude()), store.getId().toString());
        }

        findNearbyStores(116.40, 39.90, 5.0);
    }
}

测试要点:

  • 清空 GEO_KEY,确保测试数据干净
  • 预存 3 家门店
  • 查询附近 5 公里范围的门店

7. 运行结果

运行测试方法后,终端输出:

yaml 复制代码
Store ID: 100, Distance: 1.2 km
Store ID: 300, Distance: 3.4 km
Store ID: 200, Distance: 5.1 km

8. 结论

Redis 的 GEO 结构使得查询变得高效,并且适用于多种场景,如外卖推荐、网点查询、共享单车等。

总结:

  • Redis GEO 适用于高效位置查询
  • Spring Boot 结合 Redis 提供了便捷的 API
  • 通过测试可验证功能
相关推荐
爱勇宝6 分钟前
客户只想看个页面,我却做了一个静态演示发布系统
前端·javascript·后端
王中阳Go17 分钟前
老板用AI三天写到90%,让我明天上线:Java 团队怎么接这10%的烂摊子?
java
一个有理想的摸鱼选手18 分钟前
(四)路书Agnet-综合天气距离交通节奏等多因素来编排旅行路线
前端·后端·gis
神奇的程序员20 分钟前
在这个独属于ai的时代,我终究是被裁员了
前端·后端·面试
云边有个稻草人23 分钟前
从单机工具到“云+端+服务”:KDMS数据库迁移工具如何支撑大型信创项目协同作战
后端
李广坤28 分钟前
AgentScope Tool 热更新技术方案:不重启服务,实时管控 Agent 工具
后端·架构
ttwuai1 小时前
Go 后台接入 SSO 后菜单正常但接口 403,怎么排查权限链路?
开发语言·后端·golang
gugucoding1 小时前
55. 【Java】Maven:项目构建的“管家”
java·maven
65岁退休Coder1 小时前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
郑州光合科技余经理2 小时前
海外版多语言团购系统架构:主数据互通与核销边界
java·开发语言·前端·后端·系统架构·php·ai编程