简体   繁体   English

方法之间的Java JDBC连接共享/中继

[英]Java JDBC Connection Sharing/relaying between methods

I am developing an WebApp and would like to know if there is any pros/cons of sharing JDBC connection object between methods 我正在开发一个WebApp,想知道方法之间是否存在共享JDBC连接对象的优点/缺点

So the situation is 所以情况是

  • It is a WebApp and multiuser environment (aprox 1000 user using at a same time) 它是一个WebApp和多用户环境(大约同时使用1000个用户)
  • I am using a container that supports connection pooling (Weblogic Server) 我正在使用一个支持连接池的容器(Weblogic Server)
  • I use Transactions in my JDBC calls 我在JDBC调用中使用事务
  • Most of my JDBC calls are single record insert/Update but select/delete can happen in bulk 我的大多数JDBC调用都是单记录插入/更新,但是选择/删除可以批量进行

Now i have two approach 现在我有两种方法

Approach 1 Open the connection object once and relay it across the methods 方法1打开连接对象一次,并在方法之间进行中继

// Just a Pseudo Code

Cn = OpenJDBConnection() // This will open up the  connection 
obj.Task1(Cn, Param1, Param2);
obj.Task2(Cn, Param1, Param2);
obj.Task3(Cn, Param1, Param2);
Cn.close();

Approach 2 Open and close the connection in each method 方法2每种方法中打开和关闭连接

I am leaning on Approach 1 as that way i will be able to avoid some boilerplate code. 我倾向于方法1,因为这样我就可以避免一些样板代码。 but i am unsure will it be threadsafe ? 但是我不确定它是线程安全的吗? i have a poolsize of 100 connection which i think is okay for 1000 users active at a given time 我有100个连接的poolsize,我认为对于给定时间的1000个活动用户来说还可以

is there anything else too that i should be considering before adopting one of the approach 在采用其中一种方法之前,我还有什么要考虑的吗?

Consider that transactions are managed at the connection level. 请考虑在连接级别上管理事务。

For your simple use-case, approach #1 may work, but it's easy to get into a situation where, for example, you have transaction pending on the connection, and call another method which does a select on the same connection, which will cause your transaction to commit (earlier than you expected). 对于您的简单用例,方法1可能有效,但是很容易陷入这种情况,例如,您的连接上有待处理的事务,然后调用另一个对同一连接进行选择的方法,这将导致您要提交的交易(比您预期的要早)。

With properly-configured connection pooling, the overhead of releasing and re-obtaining a connection should be minmal, so I'd suggest approach #2. 使用正确配置的连接池,释放和重新获得连接的开销应该是最小的,因此我建议采用方法2。 When pooled, closing the connection doesn' really close it, it leaves it open and returns it to the pool. 合并后,关闭连接并不会真正将其关闭,而是将其保持打开状态并返回到池中。

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

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