美文网首页
SpringBoot + MongoDB

SpringBoot + MongoDB

作者: cn_moexc | 来源:发表于2018-12-25 15:54 被阅读0次

    mongodb安装及操作:菜鸟教程
    主要记录一下SpringBoot与MongoDB整合

    1. 新建一个SpringBoot项目如何创建
      pom加入以下:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    
    1. application.yml 中添加
    spring:
       data:
          mongodb:
             uri: mongodb://172.16.60.250:27017/mongo
    

    如果使用的是properties文件,需要添加spring.data.mongodb.uri:mongodb://172.16.60.250:27017/mongo
    (我用的是yml,properties这种配置方式没有试)

    1. 使用 MongoTemplate
      非常简单,只如下就可以
    @Autowired
    protected MongoTemplate mongoTemplate;
    
    public void insert(User user){
        mongoTemplate.insert(user);
    }
    

    以上代码会将User插入mongo.user中


    mongo中有一个tCustomerInfo集合,其中有5873条数据
    编写了以下代码测试一下查询速度:

    public List<TCustomerInfo> findAll() {
            
            try {
                long before = new Date().getTime();
                List<TCustomerInfo> tList = tCustomerInfoDao.findAll(TCustomerInfo.class);
                long after = new Date().getTime();
                
                System.out.println(tList.size() + "条,耗时:" + (after - before));
                
                LOGGER.info(Sign.SUCCESS_MESSAGE_OTHER);
                return tList;
            } catch (Exception e) {
                LOGGER.error(Sign.ERROR_MESSAGE_OTHER + ":" + e.getMessage());
                throw new RuntimeException(Sign.ERROR_MESSAGE_OTHER);
            }
        }
    

    执行结果如下:

    5873条,耗时:1710
    2018-12-25 15:23:17.171 [http-nio-80-exec-4] INFO  org.demons.magic.mcss.biz.impl.TCustomerInfoBizImpl-成功
    5873条,耗时:1165
    2018-12-25 15:23:51.055 [http-nio-80-exec-10] INFO  org.demons.magic.mcss.biz.impl.TCustomerInfoBizImpl-成功
    5873条,耗时:1485
    2018-12-25 15:23:59.383 [http-nio-80-exec-4] INFO  org.demons.magic.mcss.biz.impl.TCustomerInfoBizImpl-成功
    5873条,耗时:1182
    2018-12-25 15:24:03.664 [http-nio-80-exec-9] INFO  org.demons.magic.mcss.biz.impl.TCustomerInfoBizImpl-成功
    

    页面

    可以看出查询速度非常快,11.25M数据最多不过2s就可以查询完毕

    相关文章

      网友评论

          本文标题:SpringBoot + MongoDB

          本文链接:https://www.haomeiwen.com/subject/dpuflqtx.html