すべてのプロダクト
Search
ドキュメントセンター

ApsaraDB RDS:キャッシュされたデータの永続性

最終更新日:Dec 06, 2024

ApsaraDB RDS for MySQLを使用しており、データ処理を高速化し、アクセス遅延を短縮したい場合、Alibaba Cloudはキャッシュされたデータを永続化するための効率的なソリューションを提供します。 このソリューションは、ApsaraDB RDSとTair (Redis OSS互換) およびApsaraDB for Memcacheを組み合わせて、高速アクセスと永続的なストレージを確保します。 このソリューションは、高スループットと低レイテンシを備えています。

背景情報

Tair (Redis OSS互換) およびApsaraDB for Memcacheには、ApsaraDB RDSよりも次の利点があります。

  • Tair (Redis OSS互換) とApsaraDB for Memcacheは、クエリに高速に応答できます。 ほとんどの場合、クエリごとのレイテンシは数ミリ秒以内です。

  • Tair (Redis OSS互換) とApsaraDB for Memcacheのキャッシュは、より高い1秒あたりのクエリ (QPS) をサポートしています。

手順

ApsaraDB RDS for MySQLとTair (Redis OSS互換) の組み合わせ

前提条件

  • Elastic Compute Service (ECS) インスタンス、Tair (Redis OSS互換) インスタンス、およびApsaraDB RDS for MySQLインスタンスが作成されます。

    • 内部ネットワーク経由でこれらのインスタンスに接続する場合は、同じ仮想プライベートクラウド (VPC) にインスタンスを作成することを推奨します。

    • ECSインスタンス、Tair (Redis OSS互換) インスタンス、およびRDSインスタンスを作成したが、これらのインスタンスが異なるVPCにある場合、Tair (Redis OSS互換) インスタンスとRDSインスタンスのパブリックエンドポイントを有効にできます。 これにより、インターネット経由でインスタンスに接続できます。

    説明
    • この例では、ECSインスタンスのイメージバージョンはAlibaba Cloud Linux 3.2104 LTS 64ビットです。

    • この例では、プログラミング言語はPythonです。 開始する前に、ECSインスタンスにPython 3Pip 3PyMySQL、およびredis-pyをインストールします。

      次のコマンドを実行して、PyMySQLおよびredis-pyをインストールします。

      sudo pip3 install pymysql
      sudo pip3 install redis
  • IPアドレスのホワイトリストが設定されています。

  • データベースアカウントのユーザー名とパスワードは、Tair (Redis OSS互換) インスタンスとRDSインスタンスで取得されます。 詳細については、「データベースアカウントの作成と管理」および「ApsaraDB RDS For MySQLインスタンスでのアカウントの作成」をご参照ください。

手順

  1. ECSインスタンスにログインし、ビジネスシナリオをシミュレートするPythonスクリプトを作成します。 Tair (Redis OSS互換) インスタンスのキャッシュにデータが見つからない場合は、RDSインスタンスからデータを照会します。 この例では、test.pyという名前のPythonスクリプトが作成されます。

    警告

    このセクションでは、デモ用のサンプルコードを示します。 実際のビジネスコードでは、userおよびpasswordパラメーターをプレーンテキストの値に設定しないでください。 外部設定ファイルや環境変数などのメソッドを使用してパラメーターを設定し、コード内のパラメーターを参照することを推奨します。

    import json
    import redis
    import pymysql
    
    # Define the parameters that are used to connect to the RDS instance.
    mysql_host = '<Endpoint of the RDS instance>'
    mysql_user = '<Username>'
    mysql_password = '<Password>'
    mysql_port = 3306
    mysql_charset = 'utf8'
    
    # Define the parameters that are used to connect to the Tair (Redis OSS-compatible) instance.
    redis_host = '<Endpoint of the Tair (Redis OSS-compatible) instance>'
    redis_port = 6379
    # The password for the Tair (Redis OSS-compatible) instance is in the Username:Password format. If no password is not configured, set the redis_password parameter to an empty string.
    redis_password = '<Password for the Tair (Redis OSS-compatible) instance>'
    redis_db = 0
    
    
    def create_database_and_tables():
        db = pymysql.connect(host=mysql_host,
                             user=mysql_user,
                             password=mysql_password,
                             port=mysql_port,
                             charset=mysql_charset)
        cursor = db.cursor()
    
        # Create a test database.
        cursor.execute("CREATE DATABASE IF NOT EXISTS testdb;")
    
        # Select a database.
        cursor.execute("USE testdb;")
    
        # Create a test table.
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS student (
            s_id INT AUTO_INCREMENT PRIMARY KEY,
            s_name VARCHAR(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        """)
    
        # Insert data for testing.
        cursor.execute("""
        INSERT INTO student (s_name) VALUES
        ('Zhangsan'),
        ('Lisi'),
        ('Wangwu')
        ON DUPLICATE KEY UPDATE s_name = VALUES(s_name);
        """)
    
        db.commit()
        cursor.close()
        db.close()
    
    
    def fetch_from_mysql():
        db = pymysql.connect(host=mysql_host,
                             user=mysql_user,
                             password=mysql_password,
                             database="testdb",
                             port=mysql_port,
                             charset=mysql_charset)
        cursor = db.cursor()
        cursor.execute("SELECT * FROM student")
        rows = cursor.fetchall()
        cursor.close()
        db.close()
        return rows
    
    
    def cache_to_redis(redis_client, key, data):
        # Encode the data into JSON strings to store data of complex data types.
        json_data = json.dumps(data)
        # Store data to the Tair (Redis OSS-compatible) instance and set the validity period to 600 seconds, which is equivalent to 10 minutes.
        redis_client.setex(key, 600, json_data)
    
    
    def get_from_redis(redis_client, key):
        # Query data from the Tair (Redis OSS-compatible) instance.
        json_data = redis_client.get(key)
        if json_data:
            # If data is found, decode the JSON strings.
            data = json.loads(json_data)
            return data
        else:
            return None
    
    
    def main():
        # Create a client for the Tair (Redis OSS-compatible) instance.
        redis_client = redis.StrictRedis(
            host=redis_host,
            port=redis_port,
            password=redis_password,
            db=redis_db,
            decode_responses=True  # Automatically decode response data.
        )
    
        # Create a test table for the RDS instance and insert test data into the table.
        create_database_and_tables()
    
        # Define the key for storing student information in the Tair (Redis OSS-compatible) instance.
        redis_key = 'students'
    
        # Query data from the Tair (Redis OSS-compatible) instance.
        students = get_from_redis(redis_client, redis_key)
    
        if students:
            print("Query data from the Tair (Redis OSS-compatible) instance.")
            print(students)
        else:
            print("No data is found in the Tair (Redis OSS-compatible) instance. Query data from the RDS instance.")
            # Query data from the RDS instance.
            students = fetch_from_mysql()
            if students:
                print(students)
                # Cache data to the Tair (Redis OSS-compatible) instance.
                cache_to_redis(redis_client, redis_key, students)
    
    
    if __name__ == '__main__':
        main()
    
  2. test.pyを実行します。

    python3 test.py
    • test.pyを初めて実行する場合、Tair (Redis OSS互換) インスタンスのキャッシュにデータが見つからないため、RDSインスタンスからデータが読み取られます。 サンプル出力:

      No data is found in the Tair (Redis OSS-compatible) instance, but data is found in the RDS instance.
      ((1, 'Zhangsan'), (2, 'Lisi'), (3, 'Wangwu'))
    • test.pyを初めて実行しない場合、前のクエリの結果がTair (Redis OSS互換) インスタンスにキャッシュされるため、データはTair (Redis OSS互換) インスタンスから読み取られます。 サンプル出力:

      Data queried from the Tair (Redis OSS-compatible) instance:
      [[1, 'Zhangsan'], [2, 'Lisi'], [3, 'Wangwu']]

ApsaraDB RDS for MySQLとApsaraDB for Memcacheの組み合わせ

前提条件

  • ECSインスタンス、ApsaraDB for Memcacheインスタンス、およびRDSインスタンスが作成されます。 これらのインスタンスが同じVPCに作成されていることを確認します。

    説明
    • ApsaraDB for Memcacheはインターネット経由の接続をサポートしていないため、これらのインスタンスが同じVPCに作成されていることを確認する必要があります。

    • この例では、ECSインスタンスのイメージバージョンはAlibaba Cloud Linux 3.2104 LTS 64ビットです。

    • この例では、プログラミング言語はPythonです。 開始する前に、ECSインスタンスにPython 3Pip 3PyMySQLpython-memcachedをインストールします。

      次のコマンドを実行して、PyMySQLおよびpython-memcachedをインストールします。

      sudo pip3 install pymysql
      sudo pip3 install python-memcached
  • VPCのCIDRブロックは、ApsaraDB for MemcacheインスタンスおよびRDSインスタンスのIPアドレスホワイトリストに追加されます。 詳細については、「IPアドレスホワイトリストの設定」および「IPアドレスホワイトリストの設定」をご参照ください。

  • RDSインスタンスのデータベースアカウントのユーザー名とパスワードが取得されます。 詳細については、「ApsaraDB RDS For MySQLインスタンスでのアカウントの作成」をご参照ください。

  • ApsaraDB for Memcacheインスタンスでは、パスワードなしのアクセスが有効になっています。 詳細については、「パスワードなしアクセス」をご参照ください。

手順

  1. ECSインスタンスにログインし、ビジネスシナリオをシミュレートするPythonスクリプトを作成します。 ApsaraDB for Memcacheインスタンスのキャッシュにデータが見つからない場合は、RDSインスタンスからデータを照会します。 この例では、test.pyという名前のPythonスクリプトが作成されます。

    警告

    このセクションでは、デモ用のサンプルコードを示します。 実際のビジネスコードでは、userおよびpasswordパラメーターをプレーンテキストの値に設定しないでください。 外部設定ファイルや環境変数などのメソッドを使用してパラメーターを設定し、コード内のパラメーターを参照することを推奨します。

    import json
    import pymysql
    import memcache
    
    # Define the parameters that are used to connect to the RDS instance.
    mysql_host = '<Endpoint of the RDS instance>'
    mysql_user = '<Username>'
    mysql_password = '<Password>'
    mysql_port = 3306
    mysql_charset = 'utf8'
    
    # Define the parameters that are used to connect to the ApsaraDB for Memcache instance.
    memcache_host = '<Endpoint of the ApsaraDB for Memcache instance>:<Port>'
    
    
    def create_database_and_tables():
        db = pymysql.connect(host=mysql_host,
                             user=mysql_user,
                             password=mysql_password,
                             port=mysql_port,
                             charset=mysql_charset)
        cursor = db.cursor()
    
        # Create a test database.
        cursor.execute("CREATE DATABASE IF NOT EXISTS testdb;")
    
        # Select a database.
        cursor.execute("USE testdb;")
    
        # Create a test table.
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS student (
            s_id INT AUTO_INCREMENT PRIMARY KEY,
            s_name VARCHAR(255) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        """)
    
        # Insert data for testing.
        cursor.execute("""
        INSERT INTO student (s_name) VALUES
        ('Zhangsan'),
        ('Lisi'),
        ('Wangwu')
        ON DUPLICATE KEY UPDATE s_name = VALUES(s_name);
        """)
    
        db.commit()
        cursor.close()
        db.close()
    
    
    def fetch_from_mysql():
        db = pymysql.connect(host=mysql_host,
                             user=mysql_user,
                             password=mysql_password,
                             database="testdb",
                             port=mysql_port,
                             charset=mysql_charset)
        cursor = db.cursor()
        cursor.execute("SELECT * FROM student")
        rows = cursor.fetchall()
        cursor.close()
        db.close()
        return rows
    
    
    def cache_to_memcache(memcache_client, key, data):
        # Encode the data into JSON strings to store data of complex data types.
        json_data = json.dumps(data)
        Store data to the ApsaraDB for Memcache instance and set the validity period to 600 seconds, which is equivalent to 10 minutes.
        memcache_client.set(key, json_data, time=600)
    
    
    def get_from_memcache(memcache_client, key):
        # Query data from the ApsaraDB for Memcache instance.
        json_data = memcache_client.get(key)
        if json_data:
            # If data is found, decode the JSON strings.
            data = json.loads(json_data)
            return data
        else:
            return None
    
    
    def main():
        # Create a client for the ApsaraDB for Memcache instance.
        memcache_client = memcache.Client([memcache_host], debug=0)
    
        # Create a test table for the RDS instance and insert test data into the table.
        create_database_and_tables()
    
        # Define the key for storing student information in the ApsaraDB for Memcache instance.
        memcache_key = 'students'
    
        # Query data from the ApsaraDB for Memcache instance.
        students = get_from_memcache(memcache_client, memcache_key)
    
        if students:
            print("Query data from the ApsaraDB for Memcache instance.")
            print(students)
        else:
            print("No data is found in the ApsaraDB for Memcache instance. Query data from the RDS instance.")
            # Query data from the RDS instance.
            students = fetch_from_mysql()
            if students:
                print(students)
                # Cache data to the ApsaraDB for Memcache instance.
                cache_to_memcache(memcache_client, memcache_key, students)
    
    
    if __name__ == '__main__':
        main()
    
  2. test.pyを実行します。

    python3 test.py
    • test.pyを初めて実行する場合、ApsaraDB for Memcacheインスタンスのキャッシュにデータが見つからないため、RDSインスタンスからデータが読み取られます。 サンプル出力:

      No data is found in the ApsaraDB for Memcache instance, but data is found in the RDS instance.
      ((1, 'Zhangsan'), (2, 'Lisi'), (3, 'Wangwu'))
    • test.pyを初めて実行しない場合、前のクエリの結果がApsaraDB for Memcacheインスタンスにキャッシュされるため、ApsaraDB for Memcacheインスタンスからデータが読み取られます。 サンプル出力:

      Data queried from the ApsaraDB for Memcache instance:
      [[1, 'Zhangsan'], [2, 'Lisi'], [3, 'Wangwu']]

関連ドキュメント