java - HtppServlet 和 MongoClient

标签 java mongodb servlets

我正在尝试使用 Jetty 和 HttpServlet 创建一个简单的 API 后端。我读过herehere关于 HttpServlet 线程安全的详细信息 普遍的共识似乎是,这是处理 HttpServlert 中变量访问的正确方法:

public class MyServlet extends HttpServlet {
    private static Object thisIsNotThreadsafe;
    private Object thisIsAlsoNotThreadsafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadsafe;

        thisIsNotThreadsafe = request.getParameter("foo"); // BAD! Shared among all requests.
        thisIsAlsoNotThreadsafe = request.getParameter("foo"); // BAD! Shared among all requests.
        thisIsThreadsafe = request.getParameter("foo"); // Good.
    }
}

我想做的是创建一个新的 MongoClient :

MongoClient mongoClient = new MongoClient("localhost", 27017);

我可以将其设为“全局变量”,但这不是线程安全的。每次调用 doGet 或 doPost 时,我都可以创建一个新实例。但 MongoDB 的 Java 驱动程序文档似乎也建议不要这样做:

A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.

解决这个问题的最佳方法是什么?

最佳答案

如果 MongoClient 实例是线程安全的,并且可以由多个线程共享而不会成为并发瓶颈,那么您可以为共享的 MongoClient 实例实现 Singleton 包装器。

根据 Mongo 文档的说法,这将是“最正确”的方法,特别是如果您有/可能有多个 servlet 类。

如果 MongoClient 实例不是线程安全的,等等,那么您需要为 MongoClient 实例实现某种(线程安全)连接池。

<小时/>

如果您使用的框架支持依赖注入(inject) (DI),那么还有其他解决方案可以避免显式单例和池的一些问题。

关于java - HtppServlet 和 MongoClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928153/

相关文章:

node.js - Mongoose :CastError:对于值 "{ value: ' x' }"at path "项,转换到嵌入失败”

java - 如何从ModelNode结果中获取特定对象

java - Spring:从文件中读取属性为什么执行 Condition::match

java - ArrayList 类与 Java 主文件分开

javascript - 使用 POST 从数据库中检索指定的项目

mongodb - 监视 MongoDB 更改流

java - servlet 到 SQL Server 的许多连接,它们一起工作,导致 javaw.exe 过度上升

tomcat - 在 JAX-RS 资源中获取 ServletContext

java - FileNotFoundException(权限被拒绝)

java - 如何使用 JPA/Hibernate 在 child 的 id 中引用 parent 的 id?