java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Redis附近位置查找

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

作者:neoooo

Redis 提供了 GEO 数据结构,可以高效地存储和查询地理位置数据,本文将介绍如何使用 Spring Boot + Redis 来实现附近位置查找,需要的可以了解下

1. 引言

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

Redis GEO 的核心优势

2. 技术选型

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

3. 环境准备

Redis 安装

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

# 使用 Docker 启动 Redis
$ docker run -d --name redis -p 6379:6379 redis:latest

4. Spring Boot 配置 Redis

4.1 引入依赖

pom.xml 中添加 Redis 依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

4.2 配置 Redis 连接

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

spring:
  redis:
    host: localhost
    port: 6379
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms

注意:

5. 编写业务代码

5.1 定义 Store 门店实体

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Store {
    private Long id;
    private String name;
    private double longitude;
    private double latitude;
    private String address;
}

说明:

5.2 编写 Redis GEO 相关操作

1. 添加门店数据到 Redis

@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()
    );
}

注意事项:

2. 查询附近门店

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;
}

说明:

6. 编写单元测试

@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);
    }
}

测试要点:

7. 运行结果

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

Store ID: 100, Distance: 1.2 km
Store ID: 300, Distance: 3.4 km
Store ID: 200, Distance: 5.1 km

8. 结论

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

总结:

到此这篇关于SpringBoot整合Redis实现附近位置查找(LBS)功能的文章就介绍到这了,更多相关SpringBoot Redis附近位置查找内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文