栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mongobd安装及JAVA调用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mongobd安装及JAVA调用

Mongodb安装

下载Mongodb

注:linux版本与mongodb版本冲突问题,需要选择合适的版本

Linux CentOS Linux release 7.9.2009 (Core)下载mongodb包

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.2.4.tgz

解压安装

解压和移动mongodb至目录 /xxx/xxx/xxx/mongodb

tar -zxvf mongodb-linux-x86_64-rhel70-3.2.4.tgz

配置环境变量

系统profile配置 mongodb系统配置

vi /etc/profile  

export MONGODB_HOME=/xxx/xxx/xxx/mongodb/mongodb  

export PATH=$PATH:$MONGODB_HOME/bin  

重启系统环境

source /etc/profile

新建mongodb.conf 配置

新建配置cd xxx/mongodb/bin

vi mongodb.conf  

#数据文件存放目录

dbpath = /xxx/xxx/xxx/mongodb/data/db   

#日志文件存放目录

logpath = /xxx/xxx/xxx/mongodb/logs/mongodb.log  

#端口

port = 27017   

#以守护程序的方式启用,即在后台运行

fork = true    

nohttpinterface = true 

启动mongodb服务

cd  xxx/mongodb/bin

./mongod -f mongodb.conf

Mongodb与关系型数据库对比

场景

Mongodb

关系型数据库

亿级别以上数据量

轻松支持,可达百亿级  

要努力一下,分库分表        

灵活表结构       

Entity Key/Value表,关联查询难

轻松支持                    

高并发读         

轻松支持  

需要优化                    

高并发写         

轻松支持  

需要优化                    

跨地区集群       

轻松支持  

需要定制方案                

分片集群         

轻松支持  

需要中间件                  

聚合计算         

功能强大  

使用Group By,能力有限      

大宽表           

轻松支持  

性能受限                    

Mongodb应用场景
  1. 日志记录(监控日志,业务日志,调用链日志等)
  2. 系统数据(内存,IO,CPU,网络等数据等)
  3. 低价值数据(地市信息,坐标信息,公交站点信息等)
  4. 无强业务关联数据(商品类目,商品属性等)
  5. 社交信息(用户信息,联系人,群组信息,朋友圈信息,附近的人、地点,点互动信息等).
  6. 物联网数据(智能设备信息,设备汇报的日志信息等)
  7. 视频直播 (用户信息,点互动信息等)
  8. ...
  9. ...

Java接入使用

POM JAR导入

        org.mongodb

        mongo-java-driver

        3.0.2

JAVA DEMO使用

官方学习参考链接

https://docs.mongodb.com/manual/reference/method/js-collection

创建DB链接

private static final String collection = "mycollection";//数据库链接名称

private static MongoClient mongoClient;

private static MongoDatabase db;

static{

    if(mongoClient ==null){

         try {

                   MongoClientOptions options = new MongoClientOptions.Builder()

                   .socketKeepAlive(true)   // 是否保持长链接

                    .connectionsPerHost(100) // 连接池设置为100

                    .connectTimeout(15000)   // 连接超时时间

                    .maxWaitTime(1000*60*2)  // 长链接的最大等待时间

                    .socketTimeout(0)        // 套接字超时时间,0无限

                      // 线程队列数,如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误

                    .threadsAllowedToBlockForConnectionMultiplier(10000)

                    .writeConcern(WriteConcern.SAFE)//

                    .build();

                   mongoClient =                    new MongoClient(newServerAddress(MfcdllConfig.getMongodbHost(),MfcdllConfig.getMongodbIp()),options);

                   db = mongoClient.getDatabase(MfcdllConfig.getMongodb());

         } catch (Exception e) {

                   e.printStackTrace();

         }

    }

}

创建索引

Public static void createIndex(String key,Integer sort,Long expireTime){

          MongoCollection coll = db.getCollection(coolection);

          document indexOptions = new document();

          indexOptions.put(key,sort);

          if(expireTime>0){

                    // 创建索引并设置数据有效期,过期后自动删除数据

                    coll.createIndex(indexOptions,new IndexOptions().expireAfter(expireTime,                     TimeUnit.SECONDS));

          }else{

          coll.createIndex(indexOptions);

          }

}

Public static void createGroupIndex(String indexs,Long expireTime){

          MongoCollection coll = db.getCollection(coolection);

          document indexOptions = new document();

          String[] idxValue = indexs.split(",");

          for(String indVal :idxValue){

                    String[] idxVal = indVal.split(":");

                    String name1 = idxVal[0];

                    Integer sort1 = -1;

                    if(idxVal.length==2){

                              sort1 = Integer.valueOf(idxVal[1]);

                    }

                    indexOptions.put(name1, sort1);

          }

          if(expireTime>0){

                    // 创建索引并设置数据有效期,过期后自动删除数据

                    coll.createIndex(indexOptions,new IndexOptions().expireAfter(expireTime,                     TimeUnit.SECONDS));

          }else{

          coll.createIndex(indexOptions);

          }

}

查询索引

public static ListIndexesIterable getIndexs(){

          MongoCollection coll = db.getCollection(collection);

          return coll.listIndexes();

}

删除索引

public static void deleteIndex(String indexKey){

          MongoCollection coll = db.getCollection(collection);

          coll.dropIndex(indexKey);

}

插入数据

public static  void insert(Message message){

          MongoCollection coll = db.getCollection(collection);

           //getMap  将对象转换成 map集合

          document doc = new document(getMap(message));

          coll.insertOne(doc);

}

更新数据

public static void updateOne(Message message){

          MongoCollection coll = db.getCollection(collection);

           //getMap  将对象转换成 map集合

          document update = new document(getMap(message));

          Bson filter = Filters.eq("_id", message.get_id());

          coll.updateOne(filter, new document("$set",update));

}

更新MANY

public static void updateMore(Message message){

          MongoCollection coll = db.getCollection(collection);

          document update = new document(getMap(message));

          document filter = new document();

          filter.put("traceId", message.getTraceId());

          coll.updateMany(filter, new document("$set",update));

}

删除数据

public static void deleteOne(Long _id){

          MongoCollection coll = db.getCollection(collection);

          Bson filter = Filters.eq("_id", _id);

          coll.deleteOne(filter);

}

删除MANY

public static void deleteMany(Message message){

          MongoCollection coll = db.getCollection(collection);

          document filter = new document();

          filter.put("traceId",message.getTraceId());

          coll.deleteMany(filter);

}

查询数据

查询使用说明:

注:document  内部实现是Map

1.$gt:大于;$lt:小于;$gte:大于或等于;$lte:小于或等于;$ne:不等于

例:  {“key”:{“$gte”:1}}

2.$in:在数组内;$nin:不在数组内  value 是数组

例:  {“key”:{“$in”:[1]}}

3.$mod:取模运算 如: key%10==1

例:  {“key”:{“$mod”:[10,1]}} 

4.$exists:是否存在 true 存在,false 不存在

例:  {“key”:{ “$exists”:true}} 

5.正则匹配查询,如模糊匹配“test”数据

例:  {“key”:”^.*test.*$”}

6.$not:取反及组合 如:查询key取模不等于1的数据

例:  {“key”:{$not:{$mod:[10,1] } } }

public static  List getMessages(Message message,int pageSzie,int pageNm){

          MongoCollection coll = db.getCollection(collection);

          document  dbo = getQuery(message);

          document  sort = new document ();

          sort.put("startTime", 1);

          sort.put("sequence", 1);

          MongoCursor  dbCursor = null;

          if(pageSzie>0&&pageNm>0){

                    coll.find(dbo).limit(pageSzie).skip((pageNm-1)*pageSzie).sort(sort).iterator();

          }else{

                    coll.find(dbo).sort(sort).iterator();

          }

          List listMessage = new ArrayList();

          while(dbCursor!=null && dbCursor.hasNext()){

                    listMessage.add(toMessage(dbCursor.next()));

          }

          return listMessage;

}

private static document  getQuery(Message message){

          document   dbo = new document ();

          if(message.getTraceId()!=null&&!"".equals(message.getTraceId())){

                    dbo.put("traceId", message.getTraceId());

          }

           //模糊查询支持正则

          if(message.getClassName()!=null&&!"".equals(message.getClassName())){

                    Pattern pattern=Pattern.compile("^.*"+message.getClassName()+".*$");  

                    dbo.put("className", pattern);

          }

          //$gt:大于;$lt:小于;$gte:大于或等于;$lte:小于或等于;$ne:不等于

          if(message.getSequence()!=null){

                    Map map = new HashMap();

                    map.put("$gte", message.getSequence());

                    dbo.put("sequence", map);

          }

           

          return dbo;

}

统计数据

public static Long getCount(Message message){

          MongoCollection coll = db.getCollection(collection);

          document  dbo = getQuery(message);

          return coll.count(dbo);

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/439349.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号