2016-06-24 3 views
0

アプリケーション全体で使用可能な任意のオブジェクト。彼らのドキュメントでは、彼らは言いました、メイクmongoClientオブジェクト/こんにちは、私はのMongoDBのJavaドライバーで働いています

The MongoClient class is designed to be thread safe and shared among threads. 
Typically you create only 1 instance for a given database cluster and use it across 
your application. 

私はこのオブジェクトをすべてのユーザが利用できるようにしたいと思います。これどうやってするの?

答えて

1

これを行う最善の方法は、シングルトンデザインパターンを使用することです。これはコードです

public class MongoDBManager { 
    public MongoClient mongoClient = null; 
    String host = "127.0.0.1"; 
    static MongoDBManager mongo=new MongoDBManager(); 
    private MongoDBManager() { 
     try { 
      mongoClient = new MongoClient(host , 27017); 
      } catch (UnknownHostException e) { 
      System.err.println("Connection errors"); 
      e.printStackTrace(); 
     } 
    } 

    public static MongoDBManager getInstance(){ 
     return mongo; 
    } 
} 

接続する必要がある場合はいつでも電話するMongoDBManager.getInstance() 1つのオブジェクトだけが使用されます。

関連する問題