色破飞机 发表于 2018-10-28 08:41:01

实例:MongoDB与Tomcat的结合更便捷

  在用户使用MongoDB时,同样希望使用他们钟爱的Web应用服务器Tomcat。这种需求绝不是毫无意义的,下面即为一个同时使用Tomcat与MongoDB的例子。
  如果用户希望能够将web应用部署到一系列不同的环境中,需要Web应用服务器必须具备灵活性。这里能够想到的最简单方式为从web应用的web.xml文件中读取配置信息。
  一个Mongo对象实例中包含与数据库的多个连接,因此即使在多线程情况下用户也只需要一个Mongo类对象。
  web.xml 代码片段:
  
  mongo.hosts
  java.lang.Integer
  2
  
  
  mongo.slave
  java.lang.Boolean
  true
  
  
  mongo.host.address.0
  java.lang.String
  somehost.meh.feh
  
  MongoService 代码片段:
  private final Mongo mongo;
  public MongoService() throws UnknownHostException, NamingException {
  ArrayList addrs = new ArrayList();
  int hosts = ContextUtil.getEntryAsInt("mongo.hosts");
  for (int i = 0; i < hosts; i++) {
  String address = ContextUtil.getEntryAsString(&quot;mongo.host.address.&quot; + i);
  int port = ContextUtil.getEntryAsInt(&quot;mongo.host.port.&quot; + i);
  addrs.add(new ServerAddress(address, port));
  }
  mongo = new Mongo(addrs);
  //if we have more 1 instance, then lets check the slave reads ok param
  if(hosts > 1) {
  if(ContextUtil.getEntryAsBoolean(&quot;mongo.slave&quot;)) {
  mongo.slaveOk();
  }
  }
  }
  public DB getDb(String dbName) {
  return mongo.getDB(dbName);
  }
  之后,通过数据存取对象,用户可以对关联的数据库进行确定并验证。
  XxxDAO 代码片段:
  try {
  mongoService = new MongoService();
  db = mongoService.getDb(&quot;myDB&quot;);
  boolean authenticated = db.authenticate(ContextUtil.getEntryAsString(&quot;mongo.myDB.username&quot;), ContextUtil.getEntryAsString(&quot;mongo.myDB.password&quot;).toCharArray());
  }
  通过以上工作可以证明,这种方式极其便捷,可以非常方便地连接到Mongo。

页: [1]
查看完整版本: 实例:MongoDB与Tomcat的结合更便捷