MongoDB - Java |如何管理连接 [英] MongoDB - Java | How to manage the connection

查看:704
本文介绍了MongoDB - Java |如何管理连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Java的MongoDB,并且对我的连接有一些问题和疑问。首先,我应该如何连接到Mongo?我应该使用静态客户端并将其保持打开状态吗?因为连接需要500ms。因此,当用户需要数据时始终连接它并不是最好的主意,是吗?

I am using MongoDB with Java and have some problems and questions about my connection. First of all, how should I connect to Mongo? Should I use a static client and leave it open? Because it takes like 500ms to connect. So it isn't the best idea to always connect it when users want data, is it?

但下一个问题是如下。当我执行一些查询时,我收到错误消息 java.lang.IllegalStateException:池已关闭 java.lang.IllegalStateException:state应为:开

But the next problem is following. When I do some querys i get the error message java.lang.IllegalStateException: The pool is closed or java.lang.IllegalStateException: state should be: open.

那么,我应该如何管理我的整个MongoDB连接内容呢?始终等待500毫秒是缓慢和重新启动服务器的方式,就像10连接不是那么好。还有其他好办法吗?

So, how should I manage my whole MongoDB connection stuff? Always wait 500ms is way to slow and restart the server after like 10 connections isn't that good. Are there any other good ways?

感谢您的帮助!

推荐答案


我应该如何连接到Mongo?

how should I connect to Mongo?

听起来,你已经在使用 MongoClient ,这是一个很好的方法。

As it sounds, you're already using MongoClient, its a good way to go.

MongoClient 类设计为线程安全并在线程之间共享。通常,您只为给定的数据库集群创建一个实例,并在整个应用程序中使用它。

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.


我应该使用静态客户端并保持打开状态?

Should I use a static client and leave it open?

MongoClient 实例实际上代表了与数据库的连接池;即使有多个线程,你也只需要MongoClient类的一个实例。

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.


我是否需要明确关闭连接?

不,你没有。那也应该解决你得到的错误。

No, you don't. And that as well should resolve the error that you're getting.

这里是一个快速浏览使用MongoClient连接。

Here is a Quick Tour on making the connection using MongoClient.

这篇关于MongoDB - Java |如何管理连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆