gpt4 book ai didi

database - 最大连接池是否也限制了与数据库的最大连接数?

转载 作者:行者123 更新时间:2023-12-02 09:47:24 24 4
gpt4 key购买 nike

我正在使用带有超过 1000 个并发用户的 Spring Boot 应用程序的 hikari cp。
我已经设置了最大池大小-

spring.datasource.hikari.maximum-pool-size=300

当我使用 mysql 查看进程列表时
show processlist;

它显示最大 300 等于池大小。它永远不会增加超过最大池。这是有意的吗?
我认为池大小意味着维护连接,以便在需要对数据库的 future 请求时可以重用连接,但在需要时可以建立更多连接。

此外,当我删除最大池配置时,我立即得到-

HikariPool-0 - Connection is not available, request timed out after 30000ms.



如何解决此问题。提前致谢。

最佳答案

是的,它是有意的。引用 documentation :

This property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. A reasonable value for this is best determined by your execution environment. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. Please read about pool sizing. Default: 10



所以基本上,当所有 300 个连接都在使用中,并且您尝试建立第 301 个连接时,Hikari 不会创建一个新连接(因为 maximumPoolSize 是绝对最大值),但它会等待(默认情况下为 30 秒) ) 直到连接再次可用。

这也解释了为什么您会收到您提到的异常,因为默认值(未配置 maximumPoolSize 时)是 10 个连接,您可能会立即达到。

要解决此问题,您必须找出这些连接被阻止超过 30 秒的原因。即使在1000个并发用户的情况下,如果您的查询花费几毫秒或最多几秒钟,应该没有问题。

增加池大小

如果您要调用需要很长时间的非常复杂的查询,则有几种可能性。第一个是增加池大小。然而这是 不推荐 ,因为计算最大池大小的推荐公式是:
connections = ((core_count * 2) + effective_spindle_count)

引用 About Pool Sizing文章:

A formula which has held up pretty well across a lot of benchmarks for years is that for optimal throughput the number of active connections should be somewhere near ((core_count * 2) + effective_spindle_count). Core count should not include HT threads, even if hyperthreading is enabled. Effective spindle count is zero if the active data set is fully cached, and approaches the actual number of spindles as the cache hit rate falls. ... There hasn't been any analysis so far regarding how well the formula works with SSDs.



正如同一篇文章中所述,这意味着带有 1 个硬盘的 4 核服务器应该只有大约 10 个连接。即使您可能有更多内核,我假设您没有足够的内核来保证您建立的 300 个连接,更不用说进一步增加它了。

增加连接超时

另一种可能是增加连接超时。前面说过,当所有连接都在使用时,默认会等待30秒,也就是连接超时。

您可以增加此值,以便应用程序在超时之前等待更长时间。如果您的复杂查询需要 20 秒,并且您有 300 和 1000 个并发用户的连接池,则理论上您应该将连接超时配置为至少 20 * 1000 / 300 = 67 seconds .

但是请注意,这意味着您的应用程序可能需要很长时间才能向用户显示响应。如果在复杂查询完成之前有 67 秒的连接超时和额外的 20 秒,您的用户可能需要等待一分半钟。

提高执行时间

如前所述,您的主要目标是找出为什么您的查询需要这么长时间。连接池为 300,连接超时为 30 秒和 1000 个并发用户,这意味着您的查询至少需要 9 秒 在完成之前,这是很多。

尝试通过以下方式改善执行时间:
  • 添加适当的索引。
  • 正确编写查询。
  • 改进数据库硬件(磁盘、内核、网络等)
  • 通过引入分页来限制您正在处理的记录数量,...。
  • 分工。看看是否可以将查询拆分为较小的查询,这些查询会产生中间结果,然后可以在另一个查询中使用等等。只要您不在事务中工作,连接就会在两者之间被释放,从而允许您以牺牲一些性能为代价为多个用户提供服务。
  • 使用缓存
  • 预先计算结果:如果您正在进行一些资源密集型计算,您可以尝试在应用程序不经常使用的时候预先计算结果,例如。在晚上,并将这些结果存储在不同的表中,以便于查询。
  • ...
  • 关于database - 最大连接池是否也限制了与数据库的最大连接数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52420033/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com