Spring MongoDB查询附近的人功能实现
Spring MongoDB简易实现查询附近的人功能
文章目录
- 1.准备
- 2.搭建基础结构并编写代码
- 3.测试接口
- 1.分别存入3位用户
- 2.测试使用id查用户
- 3.使用广东博物馆西门的坐标测试附近有多少用户
- 3.1查1km内有多少用户
- 3.2查5km内有多少用户
- 4.退出1号看看,广东博物馆西门1km内还有多少用户
1.准备
1.创建一个springboot项目,准备一些用户坐标点数据,本案例使用广东博物馆西门分别为(1用户),广州图书馆西门(2用户),南方日报社(3用户)
2.搭建基础结构并编写代码
JSONResult
@Data
@Accessors(chain = true)
public class JSONResult<T> implements Serializable {/** 状态值 */private Integer code;/** 提示信息 */private String msg;/** 数据 */private T data;public static <T> JSONResult<T> build(int code, String msg, T data) {return new JSONResult<T>().setCode(code).setMsg(msg).setData(data);}}
UserLocation
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "user_location")
//指定我们UserLocation这个实例中使用的是2dsphere二维球面的索引
@CompoundIndex(name = "location_index", def = "{'location': '2dsphere'}")
public class UserLocation implements java.io.Serializable{private static final long serialVersionUID = 4508868382007529970L;@Idprivate String id;private Long userId; //用户idprivate GeoJsonPoint location; //x:经度 y:纬度private String address; //位置描述private Long created; //创建时间private Long updated; //更新时间private Long lastUpdated; //上次更新时间}
UserLocationServiceImpl
@Service
public class UserLocationServiceImpl {@Resourceprivate MongoTemplate mongoTemplate;public String updateUserLocation(Long userId, Double longitude, Double latitude, String address) {UserLocation userLocation = new UserLocation();userLocation.setAddress(address);userLocation.setLocation(new GeoJsonPoint(longitude, latitude));userLocation.setUserId(userId);Query query = Query.query(Criteria.where("userId").is(userLocation.getUserId()));UserLocation ul = this.mongoTemplate.findOne(query, UserLocation.class);if (ul == null) {//新增----mongodb中没有该用户数据userLocation.setCreated(System.currentTimeMillis());userLocation.setUpdated(userLocation.getCreated());userLocation.setLastUpdated(userLocation.getCreated());this.mongoTemplate.save(userLocation);return userLocation.getId();} else {//更新Update update = Update.update("location", userLocation.getLocation()).set("updated", System.currentTimeMillis()).set("lastUpdated", ul.getUpdated());this.mongoTemplate.updateFirst(query, update, UserLocation.class);}return ul.getId();}}
UserLocationController
@RestController
@RequestMapping("userLocation")
public class UserLocationController {@Resourceprivate UserLocationServiceImpl userLocationService;@Resourceprivate MongoTemplate mongoTemplate;@GetMapping("alive")public JSONResult<String> alive(){return JSONResult.build(200, "用户定位上发程序还活着!!!!",null );}@PostMapping("uploadUserLocation")public JSONResult<String> uploadUserLocation(Long userId, Double longitude, Double latitude, String address){String rowId = userLocationService.updateUserLocation(userId, longitude, latitude, address);JSONResult jsonResult = JSONResult.build(200, "地址生成成功!!",rowId );return jsonResult;}@PostMapping("queryByUserId")public JSONResult queryByUserId(Long userId){Query query = Query.query(Criteria.where("userId").is(userId));UserLocation one = mongoTemplate.findOne(query, UserLocation.class);if (one == null){return JSONResult.build(200, "查无该用户坐标位置!!",null);}return JSONResult.build(200, "查询成功,查询出坐标为!!",one );}@PostMapping("queryNearbyUserFromUserLocation")public JSONResult<List<UserLocation>> queryNearbyUserFromUserLocation(Double x, Double y, Integer range) {//找到中心点GeoJsonPoint geoJsonPoint = new GeoJsonPoint(x, y);//半径---Metric为接口,里面传入他的具体实现类Distance distance = new Distance(range / 1000, Metrics.KILOMETERS);//画圆Circle circle = new Circle(geoJsonPoint, distance);Query query = Query.query(Criteria.where("location").withinSphere(circle));List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);if (userLocations.isEmpty()){return JSONResult.build(200, "该用户坐标附近没有其他人!!",null);}List<Long> ids = userLocations.stream().map(UserLocation::getUserId).collect(Collectors.toList());return JSONResult.build(200, "该用户坐标附近的用户分别为"+ids+"!!",userLocations);}@PostMapping("userExitNearby")public JSONResult<List<UserLocation>> queryUserFromUserLocation(Long userId) {mongoTemplate.remove(new Query().addCriteria(Criteria.where("userId").is(userId)),UserLocation.class);return JSONResult.build(200, "用户退出附近的人成功!!",null);}
}
3.测试接口
1.分别存入3位用户
2.测试使用id查用户
3.使用广东博物馆西门的坐标测试附近有多少用户
3.1查1km内有多少用户
3.2查5km内有多少用户
4.退出1号看看,广东博物馆西门1km内还有多少用户
那么只剩下广州图书馆的2用户啦!!!
Spring MongoDB查询附近的人功能实现相关推荐
- 使用ElasticSearch完成百万级数据查询附近的人功能
上一篇文章介绍了ElasticSearch使用Repository和ElasticSearchTemplate完成构建复杂查询条件,简单介绍了ElasticSearch使用地理位置的功能. 这一篇我们 ...
- 解密电商系统-Spring boot快速开始及核心功能介绍(下)
上次说了Spring boot快速开始及核心功能介绍,本次说说配置文件相关的. Spring Boot属性配置文件详解(一) 修改端口 # application.properties: server ...
- 七(7)探花功能-MongoDB地理位置查询-附近的人
课程总结 1.探花功能 业务需求 执行过程 2.MongoDB的地理位置查询 地理位置查询的应用场景 查询案例 3.搜附近 上报地理位置 使用MongoDB搜索附近 一. 探花左划右滑 探花功能是将推 ...
- MongoDB查询实现 笛卡尔积,Union All 和Union 功能
转载自 MongoDB查询实现 笛卡尔积,Union All 和Union 功能 此篇文章及以后的文章大部分都是从聚合管道(aggregation pipeline)的一些语法为基础讲解的,如果不 ...
- spring mongodb内嵌文档查询
spring mongodb内嵌文档查询 代码示例 简化写法 spring mongodb内嵌文档查询示例. {"name": "zsParent", &quo ...
- 如何用 Redis 查询 “附近的人” ?
点击关注公众号:互联网架构师,后台回复 2T获取2TB学习资源! 上一篇:Alibaba开源内网高并发编程手册.pdf 来源:juejin.cn/post/6844903966061363207 作者 ...
- 简单几步,实现 Redis 查询 “附近的人”!
作者简介:万汨,饿了么资深开发工程师.iOS,Go,Java均有涉猎.目前主攻大数据开发.喜欢骑行.爬山. 前言:针对"附近的人"这一位置服务领域的应用场景,常见的可使用PG.My ...
- 基于redis(v3.2+)实现“附近的人”功能
背景介绍:目前随着电商.社交.游戏和代购等的流行,"附近的人"这一功能提供了一种便捷的方式允许同一地区或者一定距离范围内的用户进行相互交流的途径,一般都是在用户点击某个菜单或按钮时 ...
- 如何通过MongoDB自带的Explain功能提高检索性能?
MongoDB 索引 \\ 每当大家谈到数据库检索性能的时候,首先提及的就是索引,对此,MongoDB 也不例外.就像大家读一本书,或者查字典一样,索引是书的目录,让你方便的能够在上百页的书中找到自己 ...
最新文章
- linux gcc 与 glibc 的关系 glibc版本查看
- ThinkPHP5下自己写日志
- 邹伟博士出书啦!——《强化学习》从基础概念、核心原理到应用案例(文末赠书)...
- react demo
- springcloud 之服务注册与发现Eureka Server
- 为什么awt_为AWT的机器人创建DSL
- Java Jvm 中的垃圾回收机制中的思想与算法 《对Java的分析总结》-四
- 城市能源管理系统、实时监测、运行监测、负荷效应、预警管理、设备管理、设备入库、设备安装、设备检修、设备报废、设备查询、控制策略、系统集成、HTML/CSS/Bootstrap/jQuery/JS
- 27.将 VMware 服务器上的虚拟机备份到 Azure(上)
- 程序中,序列化与反序列化
- 系统动力学 matlab,MATLAB引擎在系统动力学仿真中的应用.pdf
- vga分辨率与时序配置
- 炼丹笔记三:数据增强
- 【hexo】基础教程-六-添加百度统计和Google统计
- YOLOV5:不懂代码也能使用YOLOV5跑项目
- IP和MNC地址协议
- 2020年iOS 和Android程序员请开始修炼内功
- CMD命令下获取昨日日期
- Java代码实现字符串压缩和解压缩
- jython_Jython简介,第2部分:编程要点