SpringBoot整合Redis實現(xiàn)附近位置查找(LBS)功能
1. 引言
在很多場景中,如外賣、快遞、打車等應(yīng)用,我們需要實現(xiàn)“查找附近”的功能,以便根據(jù)用戶的地理位置推薦附近的商家或服務(wù)。Redis 提供了 GEO
數(shù)據(jù)結(jié)構(gòu),可以高效地存儲和查詢地理位置數(shù)據(jù)。本文將介紹如何使用 Spring Boot + Redis 來實現(xiàn)附近位置查找。
Redis GEO 的核心優(yōu)勢
- 高效存儲:Redis 將地理空間數(shù)據(jù)存儲為有序集合,優(yōu)化了查詢性能。
- 靈活查詢:GEORADIUS 等命令支持基于半徑的搜索,并提供豐富的選項。
- 高性能:內(nèi)存存儲確保低延遲,適合實時應(yīng)用。
2. 技術(shù)選型
本項目主要使用的技術(shù)棧如下:
- Spring Boot 3.0+ - 簡化開發(fā),提高效率
- Spring Data Redis - 方便地操作 Redis
- Redis GEO - 存儲和查詢地理位置數(shù)據(jù)
- JUnit 5 - 進(jìn)行單元測試
3. 環(huán)境準(zhǔn)備
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
注意:
host
指定 Redis 服務(wù)器的地址,默認(rèn)是localhost
port
指定 Redis 的端口,默認(rèn)6379
lettuce
是 Redis 連接池配置,建議調(diào)整max-active
來優(yōu)化性能
5. 編寫業(yè)務(wù)代碼
5.1 定義 Store 門店實體
@Data @AllArgsConstructor @NoArgsConstructor public class Store { private Long id; private String name; private double longitude; private double latitude; private String address; }
說明:
longitude
和latitude
存儲經(jīng)緯度id
作為門店的唯一標(biāo)識
5.2 編寫 Redis GEO 相關(guān)操作
1. 添加門店數(shù)據(jù)到 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() ); }
注意事項:
opsForGeo().add()
方法將門店數(shù)據(jù)存入 Redisstore.getLongitude()
和store.getLatitude()
確保正確傳入store.getId().toString()
作為 key,保證唯一性
2. 查詢附近門店
public List<Store> findNearbyStores(double longitude, double latitude, double radiusKm) { // 創(chuàng)建該坐標(biāo)需要查找的半徑 Circle circle = new Circle(new Point(longitude, latitude), new Distance(radiusKm, Metrics.KILOMETERS)); // 創(chuàng)建所需結(jié)果集參數(shù) RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs() .includeDistance() //包含距離 .includeCoordinates() //包含坐標(biāo) .sortAscending() //升序排列 .limit(10); //結(jié)果集數(shù)量 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()
返回坐標(biāo)sortAscending()
按距離排序limit(10)
限制返回 10 條數(shù)據(jù)
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); } }
測試要點:
- 清空
GEO_KEY
,確保測試數(shù)據(jù)干凈 - 預(yù)存 3 家門店
- 查詢附近 5 公里范圍的門店
7. 運行結(jié)果
運行測試方法后,終端輸出:
Store ID: 100, Distance: 1.2 km
Store ID: 300, Distance: 3.4 km
Store ID: 200, Distance: 5.1 km
8. 結(jié)論
Redis 的 GEO 結(jié)構(gòu)使得查詢變得高效,并且適用于多種場景,如外賣推薦、網(wǎng)點查詢、共享單車等。
總結(jié):
- Redis GEO 適用于高效位置查詢
- Spring Boot 結(jié)合 Redis 提供了便捷的 API
- 通過測試可驗證功能
到此這篇關(guān)于SpringBoot整合Redis實現(xiàn)附近位置查找(LBS)功能的文章就介紹到這了,更多相關(guān)SpringBoot Redis附近位置查找內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot設(shè)置加載靜態(tài)資源的路徑(spring.resources.static-locations)
這篇文章主要介紹了springboot設(shè)置加載靜態(tài)資源的路徑方式(spring.resources.static-locations),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08mybatis條件構(gòu)造器(EntityWrapper)的使用方式
這篇文章主要介紹了mybatis條件構(gòu)造器(EntityWrapper)的使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03spring通過導(dǎo)入jar包和配置xml文件啟動的步驟詳解
這篇文章主要介紹了spring通過導(dǎo)入jar包和配置xml文件啟動,本文分步驟通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08Struts2開發(fā)環(huán)境搭建 附簡單登錄功能實例
這篇文章主要介紹了Struts2開發(fā)環(huán)境搭建,為大家分享一個簡單登錄功能實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11