public @Bean DatabasedMongo mongo() {
   try {
     MongoClient mongoClient = new MongoClient(mongoHosts());
     mongoClient.setReadPreference(readPreference());
     return new DatabasedMongo(mongoClient, mongoDbName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  @Override
  protected MongoClient createInstance() throws Exception {
    MongoClient mongo = initMongo();

    // 设定主从分离
    if (readSecondary) {
      mongo.setReadPreference(ReadPreference.secondaryPreferred());
    }
    // 设定写策略
    mongo.setWriteConcern(writeConcern);
    return mongo;
  }
Example #3
0
 @SuppressWarnings("deprecation")
 @Override
 public Mongo get() {
   try {
     String mongodbAddress = configuration.getString("mongodb.address");
     String[] addresses = mongodbAddress.split(",");
     ArrayList<ServerAddress> servers = new ArrayList<ServerAddress>();
     for (String address : addresses) {
       String[] addPort = address.split(":");
       String add = addPort[0];
       int port = addPort.length > 1 ? Integer.parseInt(addPort[1]) : 27017;
       servers.add(new ServerAddress(add, port));
     }
     LOGGER.info("mongo servers:" + mongodbAddress);
     //            MongoOptions mongoOptions = new MongoOptions();
     //            mongoOptions.connectionsPerHost =
     // this.configuration.getInt("mongodb.connectionsPerHost", 60);
     //            mongoOptions.socketTimeout = 60000;
     //            mongoOptions.connectTimeout = 30000;
     //            mongoOptions.autoConnectRetry = true;
     //            mongoOptions.socketKeepAlive = true;
     //            Mongo mongo = new Mongo(servers, mongoOptions);
     MongoClientOptions.Builder builder = MongoClientOptions.builder();
     builder
         .socketKeepAlive(true)
         .socketTimeout(60000)
         .connectTimeout(30000)
         .autoConnectRetry(true)
         .connectionsPerHost(this.configuration.getInt("mongodb.connectionsPerHost", 60));
     MongoClient mongoClient = new MongoClient(servers, builder.build());
     if (isReadSecondary) mongoClient.setReadPreference(ReadPreference.secondaryPreferred());
     return mongoClient;
   } catch (Throwable e) {
     LOGGER.error("failed to init mongodb", e);
     throw new ExceptionInInitializerError(e);
   }
 }