Java- 如何在大型 java 项目中管理数据库连接
Java- How to manage a database connection in a large java project
主要问题是,在一个 large/big java 项目中,多个 类 具有多个数据库连接,
我们是否应该使用全局单一连接到数据库并 运行 它直到程序结束并在程序结束时关闭它或者
我们是否应该在需要时使用多个数据库连接?
在安全性和访问方便性方面哪个更好。
在 "big" 项目中,我会使用应用程序容器来为我管理数据库连接。
安全性不仅取决于与数据库的连接。对我来说,这有点过头了。如果设计存在缺陷,例如,安全性始终是一个问题。 SQL 注射。
Should we use a global Single Connection to db and run it till the
program ends and close it at the end of program?
一般来说,在程序结束之前,您不应该为整个应用程序使用单个连接,这是一种不好的做法。
Should we use multiple db connections whenever it is required?**
是的,您需要使用多个连接并在任务完成时释放每个连接对象,即始终关闭 finally
块中的资源或使用 try-with-resources 这样他们就不会造成任何连接泄漏。
创建数据库连接的成本很高,在企业应用程序中,您需要使用连接池,它会加载特定数量启动期间的连接数,您将使用 & return 来自池的连接。您可以查看 here 更多内容。
最好将连接管理交给像Tomcat JDBC Pool.
这样的连接池
取自官方文档的优点列表,
Features added over other connection pool implementations
1.Support for highly concurrent environments and multi core/cpu systems.
2.Dynamic implementation of interface, will support java.sql and javax.sql interfaces for your runtime environment (as long as your
JDBC driver does the same), even when compiled with a lower version of
the JDK.
3.Validation intervals - we don't have to validate every single time we use the connection, we can do this when we borrow or return the
connection, just not more frequent than an interval we can configure.
4.Run-Once query, a configurable query that will be run only once, when the connection to the database is established. Very useful to
setup session settings, that you want to exist during the entire time
the connection is established.
5.Ability to configure custom interceptors. This allows you to write custom interceptors to enhance the functionality. You can use
interceptors to gather query stats, cache session states, reconnect
the connection upon failures, retry queries, cache query results, and
so on. Your options are endless and the interceptors are dynamic, not
tied to a JDK version of a java.sql/javax.sql interface.
6.High performance - we will show some differences in performance later on
7.Extremely simple, due to the very simplified implementation, the line count and source file count are very low, compare with c3p0 that
has over 200 source files(last time we checked), Tomcat jdbc has a
core of 8 files, the connection pool itself is about half that. As
bugs may occur, they will be faster to track down, and easier to fix.
Complexity reduction has been a focus from inception.
8.Asynchronous connection retrieval - you can queue your request for a connection and receive a Future back.
9.Better idle connection handling. Instead of closing connections directly, it can still pool connections and sizes the idle pool with a
smarter algorithm.
10.You can decide at what moment connections are considered abandoned, is it when the pool is full, or directly at a timeout by specifying a
pool usage threshold.
11.The abandon connection timer will reset upon a statement/query activity. Allowing a connections that is in use for a long time to not
timeout. This is achieved using the ResetAbandonedTimer
12.Close connections after they have been connected for a certain time. Age based close upon return to the pool.
13.Get JMX notifications and log entries when connections are suspected for being abandoned. This is similar to the
removeAbandonedTimeout but it doesn't take any action, only reports
the information. This is achieved using the suspectTimeout attribute.
14.Connections can be retrieved from a java.sql.Driver, javax.sql.DataSource or javax.sql.XADataSource This is achieved using
the dataSource and dataSourceJNDI attributes.
15.XA connection support
示例:
这里是关于如何为 JNDI 查找配置 资源的示例。
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="root"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>
主要问题是,在一个 large/big java 项目中,多个 类 具有多个数据库连接,
我们是否应该使用全局单一连接到数据库并 运行 它直到程序结束并在程序结束时关闭它或者 我们是否应该在需要时使用多个数据库连接? 在安全性和访问方便性方面哪个更好。
在 "big" 项目中,我会使用应用程序容器来为我管理数据库连接。 安全性不仅取决于与数据库的连接。对我来说,这有点过头了。如果设计存在缺陷,例如,安全性始终是一个问题。 SQL 注射。
Should we use a global Single Connection to db and run it till the program ends and close it at the end of program?
一般来说,在程序结束之前,您不应该为整个应用程序使用单个连接,这是一种不好的做法。
Should we use multiple db connections whenever it is required?**
是的,您需要使用多个连接并在任务完成时释放每个连接对象,即始终关闭 finally
块中的资源或使用 try-with-resources 这样他们就不会造成任何连接泄漏。
创建数据库连接的成本很高,在企业应用程序中,您需要使用连接池,它会加载特定数量启动期间的连接数,您将使用 & return 来自池的连接。您可以查看 here 更多内容。
最好将连接管理交给像Tomcat JDBC Pool.
这样的连接池取自官方文档的优点列表,
Features added over other connection pool implementations
1.Support for highly concurrent environments and multi core/cpu systems.
2.Dynamic implementation of interface, will support java.sql and javax.sql interfaces for your runtime environment (as long as your JDBC driver does the same), even when compiled with a lower version of the JDK.
3.Validation intervals - we don't have to validate every single time we use the connection, we can do this when we borrow or return the connection, just not more frequent than an interval we can configure.
4.Run-Once query, a configurable query that will be run only once, when the connection to the database is established. Very useful to setup session settings, that you want to exist during the entire time the connection is established.
5.Ability to configure custom interceptors. This allows you to write custom interceptors to enhance the functionality. You can use interceptors to gather query stats, cache session states, reconnect the connection upon failures, retry queries, cache query results, and so on. Your options are endless and the interceptors are dynamic, not tied to a JDK version of a java.sql/javax.sql interface.
6.High performance - we will show some differences in performance later on
7.Extremely simple, due to the very simplified implementation, the line count and source file count are very low, compare with c3p0 that has over 200 source files(last time we checked), Tomcat jdbc has a core of 8 files, the connection pool itself is about half that. As bugs may occur, they will be faster to track down, and easier to fix. Complexity reduction has been a focus from inception.
8.Asynchronous connection retrieval - you can queue your request for a connection and receive a Future back.
9.Better idle connection handling. Instead of closing connections directly, it can still pool connections and sizes the idle pool with a smarter algorithm.
10.You can decide at what moment connections are considered abandoned, is it when the pool is full, or directly at a timeout by specifying a pool usage threshold.
11.The abandon connection timer will reset upon a statement/query activity. Allowing a connections that is in use for a long time to not timeout. This is achieved using the ResetAbandonedTimer
12.Close connections after they have been connected for a certain time. Age based close upon return to the pool.
13.Get JMX notifications and log entries when connections are suspected for being abandoned. This is similar to the removeAbandonedTimeout but it doesn't take any action, only reports the information. This is achieved using the suspectTimeout attribute.
14.Connections can be retrieved from a java.sql.Driver, javax.sql.DataSource or javax.sql.XADataSource This is achieved using the dataSource and dataSourceJNDI attributes.
15.XA connection support
示例:
这里是关于如何为 JNDI 查找配置 资源的示例。
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="root"
password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>