当前位置: 首页 > news >正文

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;

    @Id
    private String id;
    private Long userId; //用户id
    private GeoJsonPoint location; //x:经度 y:纬度
    private String address; //位置描述
    private Long created; //创建时间
    private Long updated; //更新时间
    private Long lastUpdated; //上次更新时间

}

UserLocationServiceImpl

@Service
public class UserLocationServiceImpl   {

     @Resource
     private 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 {

    @Resource
    private UserLocationServiceImpl userLocationService;
    @Resource
    private 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用户啦!!!

相关文章:

  • 第04篇:Resources资源文件处理,再也不怕找不到文件了。
  • 【微信小程序】页面tab栏与页面内容联动
  • spring 启动了两个tomcat 端口问题分析
  • (四)JPA - JQPL 实现增删改查
  • 焦虑经济衍生冥想生意,年轻人会为“放空”买单吗?
  • linux之framebuffer(1)
  • Linux常用基本命令详解(二)-------磁盘分区和磁盘管理类命令
  • Vue:列表排序和筛选(运用计算属性和监视属性(侦听属性))
  • 难点:树的代码
  • vulnhub blogger: 1
  • php项目宝塔搭建实战ThinkAdmin通用公众号小程序后台开发框架
  • Web前端系列技术之Web APIs基础(从基础开始)⑥
  • FPGA学习笔记(四)通过数码管学习顶层模块和例化的编写
  • kafka 代码使用
  • 两个单链表相交的一系列问题
  • CentOS学习笔记 - 12. Nginx搭建Centos7.5远程repo
  • Druid 在有赞的实践
  • ECS应用管理最佳实践
  • HTTP中的ETag在移动客户端的应用
  • Javascript Math对象和Date对象常用方法详解
  • laravel5.5 视图共享数据
  • maven工程打包jar以及java jar命令的classpath使用
  • oldjun 检测网站的经验
  • Unix命令
  • 从零搭建Koa2 Server
  • 动手做个聊天室,前端工程师百无聊赖的人生
  • 聊聊directory traversal attack
  • 聊一聊前端的监控
  • 入门到放弃node系列之Hello Word篇
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 协程
  • 因为阿里,他们成了“杭漂”
  • 在electron中实现跨域请求,无需更改服务器端设置
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第9章 软件可靠性基础知识(P320~344)-思维导图】​
  • # 日期待t_最值得等的SUV奥迪Q9:空间比MPV还大,或搭4.0T,香
  • $.proxy和$.extend
  • (13)[Xamarin.Android] 不同分辨率下的图片使用概论
  • (14)学习笔记:动手深度学习(Pytorch神经网络基础)
  • (C#)Windows Shell 外壳编程系列9 - QueryInfo 扩展提示
  • (C语言)球球大作战
  • (Matlab)遗传算法优化的BP神经网络实现回归预测
  • (附源码)计算机毕业设计SSM保险客户管理系统
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (四)linux文件内容查看
  • (详细版)Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models
  • (转)linux 命令大全
  • *** 2003
  • .NET 命令行参数包含应用程序路径吗?
  • .NET企业级应用架构设计系列之应用服务器
  • .net网站发布-允许更新此预编译站点
  • .net专家(张羿专栏)
  • @基于大模型的旅游路线推荐方案
  • [20171113]修改表结构删除列相关问题4.txt
  • [Asp.net mvc]国际化