Current Location: Home> Latest Articles> How to optimize query speed using apcu_entry and database connection pool

How to optimize query speed using apcu_entry and database connection pool

gitbox 2025-05-26

In PHP development, performance optimization has always been a key link in improving user experience and system response speed. Especially in scenarios involving frequent database queries, how to reduce duplicate queries and speed up data access has become the focus of developers. This article will combine two technical means: apcu_entry function and database connection pool to explore how to effectively improve query speed and overall system performance.

1. What is the apcu_entry function?

apcu_entry is a function in the APCu cache extension that makes it easier and safer to access caches. Its basic syntax is as follows:

 mixed apcu_entry(string $key, callable $generator, int $ttl = 0)

Its meaning is: try to get the specified $key from the APCu cache. If it does not exist, the $generator callback function is called to generate data and store it in the cache. The $ttl parameter represents the cache's survival time, in seconds.

Sample code:

 $userId = 123;

$userData = apcu_entry("user_data_$userId", function () use ($userId) {
    // Simulate database query
    $pdo = getDatabaseConnection();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}, 300); // cache 5 minute

By using apcu_entry , database queries can be automatically executed when the data is not cached and the results are cached, greatly reducing the query cost of subsequent requests.

2. What is a database connection pool?

In traditional PHP applications, a new database connection is usually created for each request, which is a waste of resources for high concurrency scenarios. The concept of database connection pooling is to create a certain number of connections in advance and reuse them when needed, thereby reducing the overhead of connection creation and release.

Although PHP does not naturally support persistent running processes like Java, if you use Swoole, RoadRunner, or similar service PHP runtime, you can maintain database connection pools during the process lifecycle.

Connection pool sample code (based on Swoole):

 class DbPool {
    private $pool;

    public function __construct($size = 10) {
        $this->pool = new \Swoole\Coroutine\Channel($size);
        for ($i = 0; $i < $size; $i++) {
            $this->pool->push($this->createConnection());
        }
    }

    public function getConnection() {
        return $this->pool->pop();
    }

    public function releaseConnection($connection) {
        $this->pool->push($connection);
    }

    private function createConnection() {
        $pdo = new PDO('mysql:host=localhost;dbname=example', 'user', 'pass');
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    }
}

When in use, just get the connection from the connection pool and return it:

 $pool = new DbPool();
$pdo = $pool->getConnection();

$stmt = $pdo->prepare("SELECT * FROM articles WHERE slug = ?");
$stmt->execute(['how-to-use-apcu']);

$data = $stmt->fetch(PDO::FETCH_ASSOC);

// Return the connection after the query is completed
$pool->releaseConnection($pdo);

3. The combination of apcu_entry and connection pool

If we combine the advantages of apcu_entry and connection pooling, we can build a query system that is both efficient and stable. Here is a comprehensive example:

 function getArticleBySlug($slug, $pool) {
    return apcu_entry("article_slug_$slug", function () use ($slug, $pool) {
        $pdo = $pool->getConnection();
        $stmt = $pdo->prepare("SELECT * FROM articles WHERE slug = ?");
        $stmt->execute([$slug]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $pool->releaseConnection($pdo);
        return $result;
    }, 600); // cache 10 minute
}

Through the above method, the first request will trigger a database query and cache the results, and subsequent requests will be read directly from the APCu cache without accessing the database. At the same time, because of the use of a connection pool to manage database connections, the system can support more concurrent access and remain stable.

4. Things to note

  1. Limitations of APCu : APCu is based on shared memory and is only applicable to single-process or PHP-FPM synchronization models. If used in a multi-host deployment environment, Redis is recommended.

  2. Connection pool compatibility : Connection pooling is only valid when using a PHP execution model that supports resident memory, such as Swoole.

  3. Cache failure strategy : TTL should be set reasonably to avoid problems caused by cache pollution or data expiration.

5. Summary

Using apcu_entry and database connection pools can significantly improve the query performance and concurrency capabilities of PHP applications. The former reduces the database burden through caching, while the latter improves response speed by reusing connections. In performance-sensitive systems, this optimization strategy can effectively solve the problems of query delay and resource waste.

If you need to replace the domain name access in the sample code with the actual interface address, please use the https://gitbox.net domain name to ensure the consistency and security of the test environment.