简体   繁体   English

PHP连接的更好方法(实时或即时)

[英]Better approach for PHP Connections (Alive or Instant)

I use mysqli functions (forgive me for not using PDO) to connect to MySQL Databases. 我使用mysqli函数(原谅我不使用PDO)连接到MySQL数据库。 I was wondering which of these is a better approach? 我想知道哪种方法更好?

  1. Keeping connection alive on all classes and close the connection at the end of the php script. 使所有类上的连接保持活动状态,并在php脚本末尾关闭连接。 I mean, not closing $link till the footer. 我的意思是直到页脚不关闭$link
  2. Opening a new Connection on every classes and closing them instantly when done. 在每个课程上打开一个新的Connection,并在完成后立即关闭它们。

Please consider both resources and security. 请同时考虑资源和安全性。 Thanks! 谢谢! :) :)

Well there are multiple answers to this question around. 那么这个问题有多个答案。 I think the reason that makes php developers still can't make a good decision around closing or keeping alive, is the connection pool concept (well documented) in the other programming languages. 我认为使php开发人员仍无法在关闭或保持活动状态方面做出好的决定的原因是其他编程语言中的连接池概念(有据可查)。 For example JDBC driver, does not take care of pooling itself, But some other wrappers libraries, take care of that and create pooling. 例如JDBC驱动程序并不会自行处理池,而是会处理其他一些包装器库并创建池。 Pooling means keep reasonable connections alive for some times, and use it for new query requests. 池化意味着将合理的连接保持活动一段时间,并将其用于新的查询请求。 If all the alive connections are busy, start a new one and also don't close that, because it sounds the application is having . 如果所有活动的连接都处于繁忙状态,请启动一个新连接,也不要关闭该连接,因为这听起来应用程序正在运行。

According to this ( http://www.percona.com/blog/2006/11/12/are-php-persistent-connections-evil/ ), mysqli connections are not keep-alive by default. 据此( http://www.percona.com/blog/2006/11/12/are-php-persistent-connections-evil/),mysqli连接默认不是保持活动状态。 Meaning as soon as the query is finished, it gets closed by the mysql itself (after a little time wait). 意思是查询一旦完成,它就会被mysql本身关闭(稍等一会儿)。 Despite that, the default time wait for keeping alive, is about 8 hours in mysql and also is configurable. 尽管如此,默认的等待生存时间,在mysql中大约是8个小时,也是可以配置的。

My conclusion is: It is not only harmless to keep some connections open and reuse them, but also it is recommended. 我的结论是:保持某些连接打开并重用它们不仅无害,而且建议这样做。 But should handle something like the session scope variables and such things and also a piece of recommendation is: Its better to find an uptodate wrapper or api to handle the pooling than getting your hands greasy. 但是应该处理类似会话范围变量之类的事情,还有一条建议是:找到一个更新的包装器或api来处理池,比让您的手油腻更好。

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

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