简体   繁体   English

与SQL数据库持续通信的最有效方法

[英]Most efficient way to constantly communicate with a SQL database

So I'm working on a java program that will be constantly communicating with a SQL database. 因此,我正在研究一个Java程序,该程序将不断与SQL数据库进行通信。 The user will input their own SQL database and I'd like the load of the database and the computer itself to be as low as possible. 用户将输入他们自己的SQL数据库,我希望数据库和计算机本身的负载尽可能低。 Every X (a time indicated by the user, most likely 5 seconds - 5 minutes) the program will check for a command from the database. 程序每隔X个(由用户指示的时间,很可能是5秒-5分钟)将检查数据库中的命令。

Method A 方法一

  • Every X connect to SQL and check if there are any commands 每个X连接到SQL并检查是否有任何命令
  • Close SQL connection 关闭SQL连接

Or 要么

Method B 方法B

  • Connect to SQL when first ran 首次运行时连接到SQL
  • Keep connection open and check for commands every X 保持连接打开并每X检查一次命令
  • Close connection before shutting down 关闭前先关闭连接

I was wondering which method would be better. 我想知道哪种方法更好。

When you have a program where you cannot estimate how frequently user access the database (eg searching the database, inserting new data, deleting old data) it is always a good idea to pool the connections, ie create a number of connection at startup and closing all connections in the pool before shutting down. 当您有一个程序无法估计用户访问数据库的频率(例如,搜索数据库,插入新数据,删除旧数据)时,最好将连接池合并,即在启动和关闭时创建多个连接关闭之前,池中的所有连接。 Meanwhile connections are taken from the pool for querying the database and are released to the pool for further use. 同时,从池中获取连接以查询数据库,并将连接释放到池中以供进一步使用。 This approach avoids establishing and closing connections as they tend to be quite expensive. 这种方法避免建立和关闭连接,因为它们往往非常昂贵。 Keeping a connection alive is not a big deal and there a lot of connection pool libraries out there. 使连接保持活动状态并不重要,并且那里有很多连接池库。

Given your use case you can estimate how often a database access will occur and since the timespan between two calls seem to be rather large, it is not necesarry to use pooling. 给定您的用例,您可以估计数据库访问的频率,并且由于两次调用之间的时间间隔似乎很大,因此不必使用池。 Nonetheless it is a good practice. 尽管如此,这是一个好习惯。

The answer given refers to performance issues. 给出的答案涉及性能问题。 From my point of view method B in addition allows for a better seperation of concerns. 从我的角度来看,方法B还可以更好地分离关注点。 You have the whole connection stuff in one place and the business logic in another. 您将整个连接内容放在一个地方,将业务逻辑放在另一个地方。 No need to mix things up. 无需混淆。

Finally the pool allows for monitoring the connections. 最后,该池允许监视连接。 It will give you control over how many connections should be opened at a maximum. 它可以让您控制最大应打开多少个连接。 This may be important, eg when a single task/query needs more time than the timespan between two calls which would result in more and more connections opened. 这可能很重要,例如,当单个任务/查询需要的时间比两次调用之间的时间间隔长时,这将导致打开越来越多的连接。

I hope this gives you some answers to your question. 我希望这能给您一些答案。

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

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