简体   繁体   English

Postgres JDBC数据源实例

[英]Postgres JDBC DataSource instance

I am trying to use Postgresql with Spring. 我试图在Spring中使用Postgresql。

The way it was written was to initiate DataSource instance for each query/specific set of queries that was about to be executed. 它的编写方式是为每个要执行的查询/特定查询集启动DataSource实例。

So, the question is, is it a good idea to keep only one instance for the entire lifetime of the app or do as is now? 因此,问题是,在应用程序的整个生命周期中仅保留一个实例还是按原样执行是个好主意?

Will this lead to any memory leak if many instances are used here? 如果在这里使用许多实例,这会导致任何内存泄漏吗?

Instantiating a new DataSource for every request is a bad idea because of the overhead of establishing the connection to the database server. 为每个请求实例化一个新的DataSource是一个坏主意,因为建立与数据库服务器的连接会产生开销。 There are two design patterns that you can choose from: 您可以选择两种设计模式:

  1. A DataSource is instantiated for every session or instance of your application. 为应用程序的每个会话或实例实例化一个DataSource The advantage is that you can tailor the instance with all the details being used in the original application. 好处是您可以使用原始应用程序中使用的所有详细信息来定制实例。 The downside is that you may need many sessions - eating up resources both on the server and the client - that may be idle most of the time in between requests - but still using up those resources. 缺点是您可能需要许多会话-耗尽服务器和客户端上的资源-在两次请求之间大部分时间可能是空闲的-但仍会耗尽这些资源。
  2. Use a JNDI ( Tutorial ) connection pool . 使用JNDI教程连接池 Connections to the database are shared between sessions. 会话之间共享与数据库的连接。 This is generally much more efficient because connections stay open and will be used more intensively. 由于连接保持打开状态,并且将更密集地使用连接,因此这通常会更加有效。 On the down side, every connection has all connection details set - including user name and password - and this might not work very well with your database design. 不利的一面是,每个连接都设置了所有连接详细信息-包括用户名和密码-并且这可能不适用于您的数据库设计。

To clarify: 澄清:

  • If every user of your application has their own role in the database they should set their own role name and password when opening the connection: connection pooling is not possible and you should create a DataSource for every session. 如果应用程序的每个用户在数据库中都有自己的role ,则在打开连接时应设置自己的角色名称和密码:无法建立连接池,并且应为每个会话创建一个DataSource
  • If the users of your application use a single role in the database - say "webuser" - then you can use connection pooling with the details of that role. 如果您的应用程序用户使用数据库中的单个role (例如“ webuser”),则可以将连接池与该角色的详细信息一起使用。 This would also work if your application has a few such roles: "webuser", "webmanager", "webadmin". 如果您的应用程序具有以下几个角色,则这也将起作用:“ webuser”,“ webmanager”,“ webadmin”。 You then have to create a DataSource for each of those roles in the JNDI store. 然后,您必须为JNDI存储中的每个角色创建一个DataSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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