

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 快取資料庫查詢結果
<a name="caching-database-query-results"></a>

減少資料庫查詢延遲的常見模式是查詢快取。應用程式會透過查詢快取以取得與資料庫查詢相關聯的結果來實作查詢快取，並在快取結果時傳回這些結果。如果找不到快取結果，則會在資料庫上執行查詢、將結果填入快取中，然後將結果傳回給啟動查詢的應用程式。後續的資料庫查詢將傳回快取結果，只要它們保留在快取中。

## 何時使用查詢快取
<a name="caching-database-query-results-when-to-use"></a>

使用 ElastiCache 進行查詢快取對下列工作負載類型最有效：
+ **讀取密集型應用程式**，其中使用不常變更的資料重複執行相同的查詢。
+ **昂貴的查詢**，例如非索引查詢、彙總或多資料表聯結，其中查詢執行時間很長。
+ 將讀取卸載至 ElastiCache **的高並行情況**可降低資料庫 CPU 壓力並改善整體輸送量。

對於需要強式一致性的查詢，或需要read-after-write一致性的多陳述式交易內的查詢，不建議使用查詢快取。

## 使用 AWS 進階 JDBC 包裝函式
<a name="caching-database-query-results-jdbc-wrapper"></a>

如果您的應用程式使用 JDBC 驅動程式查詢關聯式資料庫，您可以在[AWS 進階 JDBC 包裝函](https://github.com/aws/aws-advanced-jdbc-wrapper)式中使用[遠端查詢快取外掛程式](https://github.com/aws/aws-advanced-jdbc-wrapper/blob/main/docs/using-the-jdbc-driver/using-plugins/UsingTheRemoteQueryCachePlugin.md)實作查詢快取。外掛程式會自動在 ElastiCache 中快取選取的 SQL 查詢結果集，從快取傳回結果集，而不是針對未來的查詢傳回資料庫。快取查詢結果可以減少資料庫負載，並降低平均查詢延遲，同時盡量減少應用程式程式碼變更。

## 查詢快取如何與外掛程式搭配使用
<a name="caching-database-query-results-how-it-works"></a>

遠端查詢快取外掛程式可讓查詢 PostgreSQL、MySQL 或 MariaDB 資料庫的 Java 應用程式輕鬆地在 ElastiCache 中自動快取查詢結果。您可以使用快取端點資訊設定外掛程式，並使用查詢提示指出程式碼中要快取的查詢。當外掛程式偵測到提示查詢時，如果存在 （快取命中），則會從快取傳回查詢結果。如果結果不在快取中 （快取遺漏），外掛程式會在資料庫中執行查詢、將結果儲存在快取中，並將結果傳回給您的應用程式，以便下次執行查詢時，可從快取提供結果。

## 快取提示
<a name="caching-database-query-results-hints"></a>

您可以透過為每個查詢設定提示來控制要快取的查詢。您可以直接將查詢提示套用到應用程式程式碼中具有註解字首的查詢字串：

```
/* CACHE_PARAM(ttl=300s) */ SELECT * FROM my_table WHERE id = 42
```

其中 `ttl`是以time-to-live。您也可以使用休眠和 Spring Boot 等常見架構，在預備陳述式中設定查詢提示。

## 先決條件
<a name="caching-database-query-results-prerequisites"></a>

若要在應用程式中使用遠端查詢快取外掛程式，您需要 ElastiCache for Valkey 或 Redis OSS 快取 （支援無伺服器和節點型） 以及下列相依性：
+ [AWS 進階 JDBC Wrapper](https://github.com/aws/aws-advanced-jdbc-wrapper) 3.3.0 版或更新版本。
+ [Apache Commons 集區](https://commons.apache.org/proper/commons-pool/) 2.11.1 版或更新版本。
+ [Valkey Glide](https://glide.valkey.io/) 2.3.0 版或更新版本。

## 範例：使用 外掛程式快取查詢
<a name="caching-database-query-results-example"></a>

下列範例示範如何使用 ElastiCache for Valkey 無伺服器快取啟用外掛程式並快取查詢結果 300 秒 (5 分鐘）：

```
import java.sql.*;
import java.util.Properties;

public class QueryCacheExample {
    public static void main(String[] args) throws SQLException {
        Properties props = new Properties();
        props.setProperty("user", "myuser");
        props.setProperty("password", "mypassword");

        // Enable the remote query cache plugin
        props.setProperty("wrapperPlugins", "remoteQueryCache");

        // Point to your ElastiCache endpoint
        props.setProperty("cacheEndpointAddrRw", "my-cache.serverless.use1.cache.amazonaws.com:6379");

        Connection conn = DriverManager.getConnection(
            "jdbc:aws-wrapper:postgresql://my-database.cluster-abc123.us-east-1.rds.amazonaws.com:5432/mydb",
            props
        );

        Statement stmt = conn.createStatement();

        // The SQL comment hint tells the plugin to cache this query for 300 seconds
        ResultSet rs = stmt.executeQuery(
            "/* CACHE_PARAM(ttl=300s) */ SELECT product_name, price FROM products WHERE category = 'electronics'"
        );

        while (rs.next()) {
            System.out.println(rs.getString("product_name") + ": $" + rs.getBigDecimal("price"));
        }

        rs.close();
        stmt.close();
        conn.close();
    }
}
```

第一次執行此查詢時，會從資料庫傳回結果，並在 ElastiCache 中快取。在接下來的 300 秒內，該查詢的後續執行會直接從快取提供。

## 相關資源
<a name="caching-database-query-results-related"></a>

您可以在[遠端查詢快取外掛程式文件中](https://github.com/aws/aws-advanced-jdbc-wrapper/blob/main/docs/using-the-jdbc-driver/using-plugins/UsingTheRemoteQueryCachePlugin.md)找到有關外掛程式組態的更多範例和詳細資訊。