【问题标题】:PHP RestAPI MySQL Database multiple connectionsPHP RestAPI MySQL 数据库多连接
【发布时间】:2018-06-04 02:45:52
【问题描述】:

我在 php 上有一个数据库类,它在启动时连接到数据库,用于执行查询并通过 RestAPI 请求将数据从数据库返回给用户。这里遇到的问题是,每次用户发出 HTTP 请求时,都会启动新的数据库类,并在用户使用 RestAPI 完成的每个查询上建立新的连接。

数据库类如下所示:

<?php
class DbHandler
{
    private $conn;
    function __construct()
    {
        require_once dirname(__FILE__) . '/db_connect.php';
        $db         = new DbConnect();
        $this->conn = $db->connect();
    }

    public function getSpotlight($user_id) {
      $stmt = $this->conn->prepare("SELECT *, (SELECT COUNT(*) FROM followers WHERE following = u.id) as followers, (SELECT COUNT(*) FROM posts WHERE user_id = u.id) as totalPosts from users u WHERE u.id NOT IN (select if(user_id = :var1, user_with, user_id) from friends where user_id = :var1 OR user_with = :var1) AND u.id != :var1 order by followers desc limit 10;");
      $stmt->bindParam(":var1", $user_id);
      $stmt->execute();
      $users = $stmt;
      $stmt  = null;
      return $users;
    }

DbConnect 如下所示:

<?php
class DbConnect
{
    private $conn;
    function __construct()
    {
    }

    function connect()
    {
        include_once dirname(__FILE__) . '/config.php';
        $host       = DB_HOST;
        $db_name    = DB_NAME;
        $user       = DB_USERNAME;
        $pass       = DB_PASSWORD;
        $this->conn = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        return $this->conn;
    }
}
?>

所以基本上现在当用户调用 index.php 时,会启动一个新的数据库类,每次完成查询时都会建立一个新连接,并且在请求完成后它会关闭。

直到我们有超过 1000 个用户并且每次它都会增加响应时间并且我检查了 mysql 上的进程列表并且连接在增加和退出并且新连接即将到来时,这不是问题。

我很不确定这个问题的解决方案应该是什么。有什么方法可以使它在这个 DbHandler 文件上保持持久连接?或者我们可以在 PHP 中实现其他方法。愿意听取此问题的解决方案。

【问题讨论】:

    标签: php mysql rest api connection


    【解决方案1】:

    也许这可以帮助https://www.phpfastcache.com/ 减少数据库/Web 服务调用

    您的网站有 10,000 名在线访问者,并且您的动态页面必须在每次页面加载时向数据库或网络服务发送 10,000 次相同的查询。\ 使用 phpFastCache,您的页面仅向您的 DB/WS 发送 1 个查询,并使用缓存为其他 9,999 个访问者提供服务。\您显然可以决定符合您需求的 TTL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 2010-12-13
      • 2021-12-06
      • 1970-01-01
      • 2010-10-18
      • 2015-04-23
      • 2012-09-10
      相关资源
      最近更新 更多