MongoClient 操作MongoDB replica-set
来源:互联网 发布:软件开发服务税率 编辑:程序博客网 时间:2024/05/22 08:26
对于MongoDB的Java驱动, 从2.10.0版本后,文档中提醒Mongo类将会被废除,现在开始都鼓励使用MongoClient类。
下面演示一个Java程序如何使用最新的MongoClient类来对MongoDB写操作。
首先假定已经有了一个Replica-set集群,分别是d1, d2和 d3三台虚拟机。
然后创建一个Maven构建的Java应用程序。使用了maven exec plugin用来方便执行jar包和定制参数。
看一下pom.xml:
<build> <plugins> <plugin><groupId>org.codehaus.mojo</groupId><artifactId>exec-maven-plugin</artifactId><version>1.2.1</version><executions> <execution> <goals> <goal>java</goal> </goals> </execution></executions><configuration> <mainClass>org.freebird.dbtool.App</mainClass> <arguments> <argument>d1,d2,d3</argument> </arguments></configuration> </plugin> </plugins> </build>
传递了三个参数,中间用,隔开,分别是不同的主机名称:d1, d2, d3.
看看代码初始化部分:
public static void main(String[] args) throws UnknownHostException {System.out.println(args[0]); String[] hosts = args[0].split(","); int portNumber = 27017; System.out.println(hosts[0]); System.out.println(hosts[1]); System.out.println(hosts[2]); MongoClient client = new MongoClient(Arrays.asList(new ServerAddress(hosts[0], portNumber), new ServerAddress(hosts[1], portNumber), new ServerAddress(hosts[2], portNumber))); MyApp.getInstance().setDbName("kaimei"); MyApp.getInstance().setClient(client);
这里将三个host用,分割开后,创建三个ServerAddress对象,然后构建MongoClient对象。
同时创建了一个MyApp的singleton对象,存放这个MongoClient对象,并提供了getDB()方便日后获取数据库连接。
public class MyApp { private MyApp() { } public static MyApp getInstance() { return MyAppHolder.INSTANCE; } private static class MyAppHolder { private static final MyApp INSTANCE = new MyApp(); } @Getter @Setter String dbName; @Setter MongoClient client; public DB getDB() { return client.getDB(dbName); }}
以后在任何地方需要使用连接的时候,这样使用:
public static void bind(final String address, final String userId) {DB db = MyApp.getInstance().getDB();DBCollection collection = db.getCollection(DISPLAY_COLLECTION);DBObject condition = new BasicDBObject();condition.put("address", address);DBObject field = new BasicDBObject();field.put("user_id", new ObjectId(userId));DBObject set = new BasicDBObject();set.put("$set", field);collection.update(condition, set, false, false); }
很简单吧。
- MongoClient 操作MongoDB replica-set
- MongoDB:Replica Set 之操作日志 Oplog
- MongoDB+shard+replica set
- mongodb replica set
- MongoDB Replica-set 设置
- mongodb sharding replica set
- MongoDB之Replica Set
- MongoDB Replica Set配置
- MongoDB Replica set + sharding
- mongodb replica set介绍
- Mongodb Replica Set高可用
- Mongodb Replica Set高可用
- c++ 连接 MongoDB replica-set
- MongoDB Replica Set 配置 linux
- Mongodb Replica Set + Sharding集群
- MongoDB Replica Set集群部署
- mongodb高可用Replica Set
- MongoDB 添加Replica Set实例
- 表格背景图片居中
- UML图总结
- linux设备驱动归纳总结(三):7.异步通知fasync
- cocos2d-x 1.0 2.0 代码差异
- openstack扩展API
- MongoClient 操作MongoDB replica-set
- Linux文件系统和启动过程概述
- 欧拉回路
- Android sensor架构
- 逆转一个整数的二进制表示问题[转]
- IO - 同步,异步,阻塞,非阻塞
- Introduction to Big Data
- 函数getopt(),及其参数optind
- HDU 1596 find the safest road 最短路求最大值