重学SpringBoot3-集成Redis(十一)之地理位置数据存储

news/2024/10/10 11:15:59/

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》
期待您的点赞👍收藏⭐评论✍

重学SpringBoot3-集成Redis(十一)之地理位置数据存储

  • 1. GEO 命令简介
  • 2. 项目环境配置
    • 2.1. 依赖引入
    • 2.2. Redis 配置
  • 3. GEO 数据存储和查询实现
    • 3.1. 服务层实现
    • 3.2. 控制层
  • 4. 使用示例
    • 4.1. 添加城市位置信息
    • 4.2. 查询城市位置信息
    • 4.3. 计算两城市之间的距离
    • 4.4. 查询指定城市附近的其他城市
  • 5. 总结

Redis 是一个强大的内存数据存储工具,不仅可以用来缓存和存储传统数据,还支持存储地理位置信息。通过 Redis 提供的 GEO 命令集,开发者可以方便地进行地理位置的存储、查询和计算操作。本文将介绍如何通过 Spring Boot 3 与 Redis 集成来实现地理位置数据存储功能,并进行相关的操作。


1. GEO 命令简介

Redis 的 GEO 命令主要用于存储经纬度和关联的数据,并支持基于这些数据进行距离计算和范围查询。常用的 GEO 命令有:

  • GEOADD:添加地理位置。
  • GEOPOS:获取指定成员的地理位置(经纬度)。
  • GEODIST:计算两个地理位置之间的距离。
  • GEORADIUS:以给定的经纬度为中心,查询某个范围内的地理位置。
  • GEORADIUSBYMEMBER:以给定的成员位置为中心,查询某个范围内的地理位置。

2. 项目环境配置

2.1. 依赖引入

首先,在 pom.xml 中引入 Spring Boot 3Redis 的相关依赖,具体参考重学SpringBoot3-集成Redis(一)之基本使用:

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

2.2. Redis 配置

application.yml 中配置 Redis 连接:

spring:data:redis:host: localhostport: 6379            # Redis 端口password: redis123456 # 如果有密码可以在这里配置lettuce:pool:max-active: 100    # 最大并发连接数max-idle: 50       # 最大空闲连接数min-idle: 10       # 最小空闲连接数

3. GEO 数据存储和查询实现

3.1. 服务层实现

我们将通过 StringRedisTemplate 来操作 Redis 的 GEO 命令。

java">package com.coderjia.boot310redis.service;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;/*** @author CoderJia* @create 2024/10/9 下午 10:10* @Description**/
@Service
public class GeoLocationService {@Autowiredprivate StringRedisTemplate redisTemplate;private static final String GEO_KEY = "city_locations";// 添加地理位置public void addGeoLocation(String cityName, double longitude, double latitude) {redisTemplate.opsForGeo().add(GEO_KEY, new Point(longitude, latitude), cityName);}// 获取地理位置public Point getGeoLocation(String cityName) {List<Point> positions = redisTemplate.opsForGeo().position(GEO_KEY, cityName);return positions != null && !positions.isEmpty() ? positions.get(0) : null;}// 计算两个城市之间的距离public Distance getDistance(String city1, String city2) {return redisTemplate.opsForGeo().distance(GEO_KEY, city1, city2, RedisGeoCommands.DistanceUnit.KILOMETERS);}// 查找指定范围内的城市public List<String> getCitiesWithinRadius(String cityName, double radius) {GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius(GEO_KEY, cityName, new Distance(radius, RedisGeoCommands.DistanceUnit.KILOMETERS));List<String> cities = new ArrayList<>();if (results != null) {for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : results) {cities.add(result.getContent().getName());}}return cities;}
}

3.2. 控制层

为了方便测试,我们可以通过简单的控制器来调用这些服务。

java">package com.coderjia.boot310redis.demos.web;import com.coderjia.boot310redis.service.GeoLocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Point;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author CoderJia* @create 2024/10/9 下午 10:14* @Description**/
@RestController
@RequestMapping("/geo")
public class GeoLocationController {@Autowiredprivate GeoLocationService geoLocationService;// 添加城市位置@PostMapping("/add")public String addCity(@RequestParam("city") String city, @RequestParam("lon") double lon, @RequestParam("lat") double lat) {geoLocationService.addGeoLocation(city, lon, lat);return "Added " + city;}// 查询城市位置@GetMapping("/location")public Point getCityLocation(@RequestParam("city") String city) {return geoLocationService.getGeoLocation(city);}// 计算两个城市之间的距离@GetMapping("/distance")public Distance getDistance(@RequestParam("city1") String city1, @RequestParam("city2") String city2) {return geoLocationService.getDistance(city1, city2);}// 查找指定城市附近的城市@GetMapping("/nearby")public List<String> getNearbyCities(@RequestParam("city") String city, @RequestParam("radius") double radius) {return geoLocationService.getCitiesWithinRadius(city, radius);}
}

4. 使用示例

4.1. 添加城市位置信息

通过 POST 请求添加城市位置信息,城市经纬度查询参考:https://lbs.amap.com/tools/picker

添加北上广深杭五座城市:

POST localhost:8080/geo/add?city=Beijing&lon=116.40&lat=39.90
POST localhost:8080/geo/add?city=Shanghai&lon=121.47&lat=31.23
POST localhost:8080/geo/add?city=GuangZhou&lon=113.26&lat=23.14
POST localhost:8080/geo/add?city=ShenZhen&lon=114.06&lat=22.54
POST localhost:8080/geo/add?city=HangZhou&lon=120.12&lat=30.22

添加城市位置信息

4.2. 查询城市位置信息

查询城市的经纬度信息:

GET localhost:8080/geo/location?city=Beijing

查询城市位置信息

4.3. 计算两城市之间的距离

计算两个城市之间的距离:

GET localhost:8080/geo/distance?city1=Beijing&city2=Shanghai

计算两城市之间的距离

4.4. 查询指定城市附近的其他城市

查询上海附近的其他城市(比如 200 公里内的城市):

GET localhost:8080/geo/nearby?city=Shanghai&radius=200

查询指定城市附近的其他城市

5. 总结

通过 Redis 的 GEO 命令集与 Spring Boot 3 集成,我们可以轻松实现地理位置的存储与查询功能。这种方式不仅方便,而且具有很高的性能,尤其适用于地理位置相关的应用场景,如地图服务、物流系统、附近商家查询等。

使用 Redis 进行地理位置存储的优势在于其操作简单、高效,并且能够借助 Redis 内置的命令进行实时的距离计算和范围查询。如果你的应用涉及地理信息,Redis 提供的 GEO 功能会是一个非常不错的选择。


http://www.ppmy.cn/news/1536979.html

相关文章

whistle使用实践

whistle使用实践 1.简介2.安装启动whistle3.配置代理流转浏览器流量4.访问whistle控制台5.安装https证书6.whistle使用方法控制台界面各个模块的作用代理配置方式匹配模式pattern代理IP例子1.简介 Whistle 是一个基于 Node.js 开发的网络代理工具,主要用于网络请求的代理、调…

【Sqlite】sqlite内部函数sqlite3_value_text特性

目录 ⚛️1 结论 ☪️2 说明 ☪️3 传入数值转成科学计数法 ♋3.1 只有整数部分 ♏3.2 只有小数部分 ♐3.3 整数小数 ⚛️1 结论 整数(sqlite视为int64)位数 > 20位&#xff0c;sqlite3_value_text 采用科学计数法。否则正常表示。 浮点数(sqlite视为double)的整数部…

Python 全栈开发从入门到实战进阶课程

需要课程的&#xff0c;添加文本末尾的联系方式。 以下是一份关于该课程的文档&#xff0c;其中加入了一些具体的代码示例&#xff1a; 《Python 全栈开发从入门到实战进阶课程》介绍 一、课程概述 本课程涵盖了 Python 编程的多个方面&#xff0c;包括编程基础、数据结构、…

vue3实现excel文件预览和打印功能

文章目录 一、预览excel1、安装2、使用3、代码4、效果二、打印excel1、安装2、使用3、代码4、效果三、小结在前端开发中,有时候一些业务场景中,我们有需求要去实现excel的预览和打印功能,本文将介绍在vue3中如何实现Excel文件的预览和打印。 一、预览excel 关于实现excel文…

线性回归逻辑回归-笔记

一、线性回归&#xff08;Linear Regression&#xff09; 1. 定义 线性回归是一种用于回归问题的算法&#xff0c;旨在找到输入特征与输出值之间的线性关系。它试图通过拟合一条直线来最小化预测值与真实值之间的误差。 2. 模型表示 线性回归模型假设目标变量&#xff08;输…

红灯-绿灯-重构

代码在周期内的状态&#xff1a;处于红灯状态时&#xff0c;代码不管用&#xff0c;处于绿灯状态时&#xff0c;一切都想预期的那样工作&#xff0c;但并不一定是最佳的&#xff0c;到了重构阶段&#xff0c;我们知道测试很好的覆盖了各项功能&#xff0c;可以充满信息地修改他…

Mysql 索引底层数据结构和算法

目录 索引数据结构 Hash表 二叉树 红黑树 B树 B树 索引数据结构 索引&#xff08;index&#xff09;是帮助MySQL高效获取数据的一种有序数据结构。索引是存储到表空间中&#xff0c;当我们的 sql 中的where条件用到索引的时候&#xff0c;会在存储引擎层就过滤出数据来…

Redis:cpp.redis++通用接口

Redis&#xff1a;cpp.redis通用接口 redis对象通用接口set & getexistsdelflushallkeysttlexpiretype 本博客讲解redis的C客户端redis-plus-plus&#xff0c;这个版本的客户端&#xff0c;接口和redis原生命令几乎完全一致&#xff0c;博客内部不会详细讲解每个接口的具体…