简体   繁体   中英

How to use one instance of MongoClient in java application server

According to mongodb java concurrency driver we can use one instance of MongoClient for multiple threads for example inside application servers. The only way I know to do this is to create MongoClient in static block:

static {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
}

the problem is I can't catch MongoException and return some helpfull information to user. So how to share a single instance of MongoClient between multiple threads inside Java EE application servers?

You can do one of the following:

  1. Create a service class and initiate the mongo connection lazily on first request, showing an error when you fail
  2. Add a try catch and remember the error statically (I really don't like this one! But better than failing on exception in static context)
  3. Use spring to initialize mongo (my preferred option)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM