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

ApsaraDB for Redis:クライアントを使用して、TLS (SSL) 暗号化が有効になっているApsaraDB for Redisインスタンスに接続する

最終更新日:Sep 10, 2024

クライアントを使用してApsaraDB for Redisインスタンスに接続する場合、TLS (SSL) 暗号化機能を有効にして、データリンクのセキュリティを強化し、データの整合性を確保できます。 Redis準拠のクライアントを使用して、ApsaraDB for Redisインスタンスに接続できます。 このトピックでは、共通クライアントを使用してインスタンスに接続する方法のサンプルコードを示します。

前提条件

  • TairインスタンスでTLS (SSL) 暗号化が有効になっています。 詳細については、「」「TLS暗号化の有効化」をご参照ください。

  • クライアントは、 ApsaraDB for Redisインスタンスと同じ仮想プライベートクラウド (VPC) にあるElastic Compute Service (ECS) インスタンスでホストされます。

使用上の注意

  • インスタンスのTransport Layer Security (TLS) 暗号化を有効にすると、インスタンスのパブリックエンドポイントを申請することはできません。 また、クラシッククラスターインスタンスのプライベートエンドポイントを申請することもできません。 クライアントは、VPC経由またはTLS暗号化を使用してのみインスタンスに接続できます。

  • VPCにデプロイされたインスタンスに対してパスワード不要アクセスが有効になっている場合、インスタンスと同じVPC内のクライアントはパスワードを使用せずにインスタンスにアクセスできます。

準備

  1. クライアントをホストするECSインスタンスの内部IPアドレスを ApsaraDB for Redisインスタンスのホワイトリストに追加します。 詳細については、「」「ホワイトリストの設定」をご参照ください。

  2. 次の情報を取得し、異なるプログラミング言語のクライアントコードで情報を使用します。

    項目

    説明

    インスタンスエンドポイント

    ApsaraDB for Redisインスタンスは複数のエンドポイントタイプをサポートしています。 セキュリティを高め、ネットワーク遅延を減らすために、VPCエンドポイントを使用することを推奨します。 詳細については、「エンドポイントの表示」をご参照ください。

    ポート番号

    デフォルトのポート番号6379を使用するか、カスタムポート番号を指定します。 詳細については、「接続アドレスの変更」をご参照ください。

    インスタンスアカウント (特定のクライアントではオプション)

    デフォルトでは、ApsaraDB for Redisインスタンスには、インスタンスIDにちなんで名前が付けられたデータベースアカウントがあります。 例: r-bp10noxlhcoim2 **** 。 別のデータベースアカウントを作成し、そのアカウントに必要な権限を付与できます。 詳細については、「データベースアカウントの管理」をご参照ください。

    パスワード

    パスワードの形式は、選択したアカウントによって異なります。

    • ユーザー名がインスタンスIDと同じデフォルトアカウントを使用する場合は、パスワードを入力します。

    • カスタムアカウントを使用する場合は、<user >:< password> 形式でパスワードを入力します。 たとえば、カスタムアカウントのユーザー名がtestaccountで、パスワードがRp829dlwaの場合、パスワードとしてtestaccount:Rp829dlwaを入力します。

    説明
    • リモートデスクトップマネージャー (RDM) などのサードパーティのデータベース管理ツールを使用してApsaraDB for Redisインスタンスに接続する場合は、user:password形式でパスワードを入力します。

    • パスワードを忘れた場合は、リセットできます。 詳細については、「パスワードの変更」をご参照ください。

  3. 認証局 (CA) 証明書をダウンロードします。 詳細については、「」「TLS暗号化の有効化」をご参照ください。

プロキシ接続モード

このモードは、標準インスタンス、プロキシモードのクラスターインスタンス、および読み書き分離インスタンスに適用できます。 必要に応じて、次のサンプルコードを展開します。

redis-cli

Redis-cliで ApsaraDB for redisインスタンスのTLS暗号化を有効にする前に、オープンソースのRedisをコンパイルするときにBUILD_TLSをyesに設定する必要があります。

  1. ECS インスタンスにログインします。 次に、redis-cliをダウンロードしてインストールします。

    1. 次のコマンドを実行して、必要な依存関係をインストールします。

      yum install openssl-devel gcc
    2. 次のコマンドを実行して、Redisソースコードパッケージをダウンロードします。

      wget https://download.redis.io/releases/redis-7.0.0.tar.gz
      説明

      この例では、Redis 7.0.0を使用して操作を示します。 他のバージョンをインストールできます。 詳細については、Redis公式Webサイトをご覧ください。

    3. 次のコマンドを実行して、Redisソースコードパッケージを解凍します。

      tar xzf redis-7.0.0.tar.gz
    4. 次のコマンドを実行して、オープンソースRedisのソースコードパッケージが解凍されるディレクトリに移動します。 ソースコードをコンパイルしてインストールし、BUILD_TLSをyesに設定します。

      cd redis-7.0.0&&make BUILD_TLS=yes

      ほとんどの場合、オープンソースのRedisをコンパイルしてインストールするには、2分から3分かかります。

  2. redis-cliで次のコマンドを実行して、インスタンスに接続します。

    ./src/redis-cli -h r-bp14joyeihew30****.redis.rds.aliyuncs.com -p 6379 --tls --cacert ./ApsaraDB-CA-Chain.pem

    cacertの後にCA証明書のパスを指定する必要があります。

  3. 次のコマンドを実行してパスワードを確認します。

    AUTH password

    インスタンスがredis-cliを使用して接続されている場合、OKが表示されます。

Java

Jedis 3.6.0クライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisSSLTest {
    private static SSLSocketFactory createTrustStoreSSLSocketFactory(String jksFile) throws Exception {
        KeyStore trustStore = KeyStore.getInstance("jks");
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(jksFile);
            trustStore.load(inputStream, null);
        } finally {
            inputStream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
        return sslContext.getSocketFactory();
    }

    public static void main(String[] args) throws Exception {
        // ApsaraDB-CA-Chain.jks is the name of the CA certificate file. 
        final SSLSocketFactory sslSocketFactory = createTrustStoreSSLSocketFactory("ApsaraDB-CA-Chain.jks");
        // The endpoint, port number, timeout period, and password of the instance are included in the configurations of a connection pool. 
        JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com",
            6379, 2000, "redistest:Pas***23", 0, true, sslSocketFactory, null, null);

        try (Jedis jedis = pool.getResource()) {
            jedis.set("key", "value");
            System.out.println(jedis.get("key"));
        }
    }
}

Python

redis-pyクライアントは、次のサンプルコードで使用されます。 クライアントの最新バージョンを使用することを推奨します。

接続プールからの接続

#!/bin/python
import redis

# Specify a connection pool. Replace the values of host, port, and password with the endpoint, port number, and password of the instance. 
# ApsaraDB-CA-Chain.pem is the name of the CA certificate file. 
pool = redis.ConnectionPool(connection_class=redis.connection.SSLConnection, max_connections=100,
                            host="r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com", port=6379, password="redistest:Pas***23",
                            ssl_cert_reqs=True, ssl_ca_certs="ApsaraDB-CA-Chain.pem")
client = redis.Redis(connection_pool=pool)
client.set("hi", "redis")
print client.get("hi")

通常の接続

#!/bin/python
redisのインポート

# 接続情報を指定します。 host、port、およびpasswordの値を、インスタンスのエンドポイント、ポート番号、およびパスワードに置き換えます。 
# ApsaraDB-CA-Chain.pemは、CA証明書ファイルの名前です。 
client = redis.Redis (ホスト="r-bp1zxszhcgatnx **** .redis.rds.aliyuncs.com", port=6379,
                     password="redistest:Test1234" 、ssl=True、
                    ssl_cert_reqs="required", ssl_ca_certs="ApsaraDB-CA-Chain.pem")

client.set("hello" 、"world")
print client.get("hello") 

PHP

Predisクライアントは、次のサンプルコードで使用されます。 クライアントの最新バージョンを使用することを推奨します。 PhpRedisクライアントを使用してインスタンスに接続する場合は、GitHubをご参照ください。

<?php

require __DIR__.'/predis/autoload.php';

/* Specify connection information. Replace the values of host, port, and password with the endpoint, port number, and password of the instance.
ApsaraDB-CA-Chain.pem is the name of the CA certificate.*/
$client = new Predis\Client([
    'scheme' => 'tls',
    'host'   => 'r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com',
    'port'   => 6379,
    'password' => 'redistest:Pas***23',
    'ssl'    => ['cafile' => 'ApsaraDB-CA-Chain.pem', 'verify_peer' => true],
]);
/* Replace the endpoint and the port number in the following sample code. */
//$client = new Predis\Client('tls://r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com:6379?ssl[cafile]=ApsaraDB-CA-Chain.pem&ssl[verify_peer]=1');

$client->set("hello", "world");
print $client->get("hello")."\n";

?>

C#

StackExchange.Redisクライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

System.Net.Securityを使用する

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using StackExchange.Redis;

namespace SSLTest
{
    class Program
    {
        private static bool CheckServerCertificate(object sender, X509Certificate certificate,
            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            var ca = new X509Certificate2(
                "/your path/ApsaraDB-CA-Chain/ApsaraDB-CA-Chain.pem");
            return chain.ChainElements
                .Cast<X509ChainElement>()
                .Any(x => x.Certificate.Thumbprint == ca.Thumbprint);
        }

        static void Main(string[] args)
        {
          // Specify connection information. Replace the values of host, port, and password with the endpoint, port number, and password of the instance. 
          // ApsaraDB-CA-Chain.pem is the name of the CA certificate file. 
            ConfigurationOptions config = new ConfigurationOptions()
            {
                EndPoints = {"r-bp10q23zyfriodu*****.redis.rds.aliyuncs.com:6379"},
                Password = "redistest:Pas***23",
                Ssl = true,
            };

            config.CertificateValidation += CheckServerCertificate;
            using (var conn = ConnectionMultiplexer.Connect(config))
            {
                Console.WriteLine("connected");
                var db = conn.GetDatabase();
                db.StringSet("hello", "world");
                Console.WriteLine(db.StringGet("hello"));
            }
        }
    }
}

SpringデータRedis

次のサンプルコードでは、Java 1.8と互換性のあるSpring Data Redis 2.7.12クライアントを使用しています。 クライアントの最新バージョンを使用することを推奨します。

@Configuration
public class RedisConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        // We recommend that you store the TLS certificate in the properties file. 
        String host = "r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com";
        int port = 6379;
        String password = "Pas***23";
        String trustStoreFilePath = "/path/to/ApsaraDB-CA-Chain.jks";

        ClientOptions clientOptions = ClientOptions.builder().sslOptions(
            SslOptions.builder().jdkSslProvider().truststore(new File(trustStoreFilePath)).build()).build();
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(host);
        config.setPort(port);
        config.setPassword(password);
        LettuceClientConfiguration lettuceClientConfiguration = LettuceClientConfiguration.builder()
            .clientOptions(clientOptions)
            .useSsl().build();
        return new LettuceConnectionFactory(config, lettuceClientConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    }
}

レタス

レタス6.2.4.RELEASEクライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

public class SSLExample {
    public static void main(String[] args) throws Exception {
        String host = "r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com";
        int port = 6379;
        String password = "Pas***23";
        String trustStoreFilePath = "/path/to/ApsaraDB-CA-Chain.jks";

        RedisURI uri = RedisURI.builder()
            .withHost(host)
            .withPort(port)
            .withPassword(password.toCharArray())
            .withSsl(true).build();

        SslOptions sslOptions = SslOptions.builder()
            .jdkSslProvider()
            .truststore(new File(trustStoreFilePath)).build();

        ClientOptions clientOptions = ClientOptions.builder()
            .sslOptions(sslOptions).build();
        RedisClient client = RedisClient.create(uri);
        client.setOptions(clientOptions);

        RedisCommands<String, String> sync = client.connect().sync();
        System.out.println(sync.set("key", "value"));
        System.out.println(sync.get("key"));

    }
}

行く

go-redis 9.5.1クライアントは、次のサンプルコードで使用されています。 go-redis 9.0以降の使用を推奨します。

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"crypto/tls"
	"crypto/x509"
	"github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func main() {
        caCert, err := ioutil.ReadFile("/root/ApsaraDB-CA-Chain.pem")
	if err != nil {
		fmt.Println("Error loading CA certificate:", err)
		return
	}

	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	tlsConfig := &tls.Config{
		RootCAs:            caCertPool,
		InsecureSkipVerify: true, // Not actually skipping, we check the cert in VerifyPeerCertificate
		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
			// Code copy/pasted and adapted from
			// https://github.com/golang/go/blob/81555cb4f3521b53f9de4ce15f64b77cc9df61b9/src/crypto/tls/handshake_client.go#L327-L344, but adapted to skip the hostname verification.
			// See https://github.com/golang/go/issues/21971#issuecomment-412836078.

			// If this is the first handshake on a connection, process and
			// (optionally) verify the server's certificates.
			certs := make([]*x509.Certificate, len(rawCerts))
			for i, asn1Data := range rawCerts {
				cert, err := x509.ParseCertificate(asn1Data)
				if err != nil {
					panic(err)
				}
				certs[i] = cert
			}

			opts := x509.VerifyOptions{
				Roots:         caCertPool,
				DNSName:       "", // <- skip hostname verification
				Intermediates: x509.NewCertPool(),
			}

			for i, cert := range certs {
				if i == 0 {
					continue
				}
				opts.Intermediates.AddCert(cert)
			}
			_, err := certs[0].Verify(opts)
			return err
		},
	}

	rdb := redis.NewClient(&redis.Options{
		Addr:    "r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com:6379",
		Username: "default",
		Password: "Pas***23",
		TLSConfig: tlsConfig,
	})

	err = rdb.Set(ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := rdb.Get(ctx, "key").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("key:", val)
}

直接接続モード

このモードは、直接接続モードのクラスターインスタンスにのみ適用できます。 必要に応じて、次のサンプルコードを展開します。

redis-cli

Redis-cliで ApsaraDB for redisインスタンスのTLS暗号化を有効にする前に、オープンソースのRedisをコンパイルするときにBUILD_TLSをyesに設定する必要があります。

  1. ECS インスタンスにログインします。 次に、redis-cliをダウンロードしてインストールします。

    1. 次のコマンドを実行して、必要な依存関係をインストールします。

      yum install openssl-devel gcc
    2. 次のコマンドを実行して、Redisソースコードパッケージをダウンロードします。

      wget https://download.redis.io/releases/redis-7.0.0.tar.gz
      説明

      この例では、Redis 7.0.0を使用して操作を示します。 他のバージョンをインストールできます。 詳細については、Redis公式Webサイトをご覧ください。

    3. 次のコマンドを実行して、Redisソースコードパッケージを解凍します。

      tar xzf redis-7.0.0.tar.gz
    4. 次のコマンドを実行して、オープンソースRedisのソースコードパッケージが解凍されるディレクトリに移動します。 ソースコードをコンパイルしてインストールし、BUILD_TLSをyesに設定します。

      cd redis-7.0.0&&make BUILD_TLS=yes

      ほとんどの場合、オープンソースのRedisをコンパイルしてインストールするには、2分から3分かかります。

  2. redis-cliで次のコマンドを実行して、インスタンスに接続します。

    ./src/redis-cli -h r-bp14joyeihew30****.redis.rds.aliyuncs.com -p 6379 -c --tls --cacert ./ApsaraDB-CA-Chain.pem

    cacertの後にCA証明書のパスを指定する必要があります。

  3. 次のコマンドを実行してパスワードを確認します。

    AUTH password

    インスタンスがredis-cliを使用して接続されている場合、OKが表示されます。

Java

Jedis 4.3.0クライアントは、次のサンプルコードで使用されます。 クライアントの最新バージョンを使用することを推奨します。

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import redis.clients.jedis.ConnectionPoolConfig;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterTSL {
    private static final int DEFAULT_TIMEOUT = 2000;
    private static final int DEFAULT_REDIRECTIONS = 5;
    private static final ConnectionPoolConfig jedisPoolConfig = new ConnectionPoolConfig();

    private static SSLSocketFactory createTrustStoreSSLSocketFactory(String jksFile) throws Exception {
        KeyStore trustStore = KeyStore.getInstance("jks");
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(jksFile);
            trustStore.load(inputStream, null);
        } finally {
            inputStream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
        return sslContext.getSocketFactory();
    }

    public static void main(String args[]) throws Exception{
        // Specify the maximum number of idle connections. In direct connection mode, the client directly connects to a shard of a cluster instance. Therefore, the following requirement must be met: Number of clients × Value of MaxTotal < Maximum number of connections to a single shard. 
        // Set the maximum number of connections to a shard of an ApsaraDB for Redis Community Edition instance to 10,000 and the maximum number of connections to a shard of a Tair instance to 30,000. 
        jedisPoolConfig.setMaxTotal(30);
        // Specify the maximum number of idle connections based on your business requirements. 
        jedisPoolConfig.setMaxIdle(30);
        jedisPoolConfig.setMinIdle(15);

        // Specify the private endpoint. 
        int port = 6379;
        String host = "r-2zee50zxi5iiq****.redis.rds-aliyun.rds.aliyuncs.com";
        String user = "default";
        String password = "Pas***23";

        final SSLSocketFactory sslSocketFactory = createTrustStoreSSLSocketFactory("/root/ApsaraDB-CA-Chain.jks");
        DefaultJedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder().connectionTimeoutMillis(DEFAULT_TIMEOUT)
            .socketTimeoutMillis(DEFAULT_TIMEOUT)
            .user(user).password(password)
            .ssl(true)
            .sslSocketFactory(sslSocketFactory).build();

        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
        jedisClusterNode.add(new HostAndPort(host, port));
        JedisCluster jc = new JedisCluster(jedisClusterNode, jedisClientConfig, DEFAULT_REDIRECTIONS, jedisPoolConfig);

        System.out.println(jc.set("key", "value"));
        System.out.println(jc.get("key"));

        jc.close();     // If the application exits and you want to destroy the resources, call this method. This way, the connection is closed, and the resources are released. 
    }
}

Python

redis-pyの4.3.6 (Python 3.6) クライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

#!/usr/bin/env python
from redis.cluster import RedisCluster

# Replace the values of the host and port parameters with the endpoint and port number that are used to connect to the instance. 
host = 'r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com'
port = 6379
# Replace the values of the user and pwd parameters with the username and password that are used to connect to the instance. 
user = 'default'
pwd = 'Pas***23'

rc = RedisCluster(host=host, port=port, username=user, password=pwd, ssl=True, ssl_ca_certs="/root/ApsaraDB-CA-Chain.pem")
# You can perform operations on the instance after the connection is established. The following code provides an example on how to call the set and get methods: 
rc.set('foo', 'bar')
print(rc.get('foo'))

PHP

PhpRedis 5.3.7クライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

<?php
 // Specify the private endpoint and the port number that are used to connect to the cluster instance. 
 $array = ['r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com:6379'];
 // Specify the password that is used to connect to the cluster instance. 
 $pwd = "Pas***23";
 // Specify the TLS connection information.
 $tls = ["verify_peer" => false, "verify_peer_name" => false];
 // Use the password to connect to the cluster instance. 
 $obj_cluster = new RedisCluster(NULL, $array, 1.5, 1.5, true, $pwd, $tls);

 // Display the result of the connection. 
 var_dump($obj_cluster);

 if ($obj_cluster->set("foo", "bar") == false) {
     die($obj_cluster->getLastError());
 }
 $value = $obj_cluster->get("foo");
 echo $value;
 echo "\n";
 ?>

C#

StackExchange.Redisクライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

StackExchange.Redisを使用した

using StackExchange.Redis;
using System;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace TairClient
{
    class Program
    {
        static void Main()
        {
            // Use a private endpoint to establish a connection. 
            const string Host = "r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com";
            const int Port = 6379;
            Console.WriteLine("connecting...");
            var config = new ConfigurationOptions
            {
                EndPoints = { { Host, Port } },
                Ssl = true,
                Password = "Pas***23",
            };
            config.CertificateValidation += (sender, cert, chain, errors) =>
            {
                if (errors == SslPolicyErrors.RemoteCertificateChainErrors || errors ==  SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    return true;
                }
                var caCert = LoadCertificateFromPem("/root/ApsaraDB-CA-Chain.pem");

                var isCertIssuedByTrustedCA = chain.ChainElements
                    .Cast<X509ChainElement>()
                    .Any(x => x.Certificate.Thumbprint.Equals(caCert.Thumbprint, StringComparison.OrdinalIgnoreCase));

                // Specify other verification logic.
                return isCertIssuedByTrustedCA;
            };

            using (var conn = ConnectionMultiplexer.Connect(config))
            {
                Console.WriteLine("connected");
                var db = conn.GetDatabase();
                db.StringSet("hello", "world");
                Console.WriteLine(db.StringGet("hello")); // writes: world
            }
        }

        private static X509Certificate2 LoadCertificateFromPem(string pemFilePath)
        {
            // Use a static method of X509Certificate2 to load a certificate directly from the PEM content.
            X509Certificate2 cert = X509Certificate2.CreateFromPem(File.ReadAllText(pemFilePath));
            return cert;
        }

    }
}

SpringデータRedis

次のサンプルコードでは、Java 1.8と互換性のあるSpring Data Redis 2.7.5クライアントを使用しています。 クライアントの最新バージョンを使用することを推奨します。

Spring Data Redis with Jedis (推奨)

import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfigJedis {
    private static SSLSocketFactory createTrustStoreSSLSocketFactory(String jksFile) throws Exception {
        KeyStore trustStore = KeyStore.getInstance("jks");
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(jksFile);
            trustStore.load(inputStream, null);
        } finally {
            inputStream.close();
        }

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX");
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
        return sslContext.getSocketFactory();
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory() throws Exception {
        String host = "r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com:6379";
        String user = "default";
        String password = "Pas***23";
        String trustStoreFilePath = "/root/ApsaraDB-CA-Chain.jks";

        List<String> clusterNodes = Arrays.asList(host);
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(clusterNodes);
        redisClusterConfiguration.setUsername(user);
        redisClusterConfiguration.setPassword(password);

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // Specify the maximum number of idle connections. In direct connection mode, the client directly connects to a shard of a cluster instance. Therefore, the following requirement must be met: Number of clients × Value of MaxTotal < Maximum number of connections to a single shard. 
        // Set the maximum number of connections to a shard of an ApsaraDB for Redis Community Edition instance to 10,000 and the maximum number of connections to a shard of a Tair instance to 30,000. 
        jedisPoolConfig.setMaxTotal(30);
        jedisPoolConfig.setMaxIdle(20);
        jedisPoolConfig.setMinIdle(20);

        final SSLSocketFactory sslSocketFactory = createTrustStoreSSLSocketFactory(trustStoreFilePath);
        JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().useSsl()
            .sslSocketFactory(sslSocketFactory).and().usePooling().poolConfig(jedisPoolConfig).build();

        return new JedisConnectionFactory(redisClusterConfiguration, jedisClientConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}

レタスと春のデータRedis

java.io.Fileをインポートします。io. leutter. core.ClientOptionsをインポートします。io. leutter. core.SslOptionsをインポートします。org.springframework.context.annotation.Beanをインポートします。org.springframework.context.annotation.Configurationをインポートします。org.springframework.data.redis.connection.RedisClusterConfigurationをインポートします。org.springframework.data.redis.connection.RedisConnectionFactoryをインポートします。org.springframework.data.redis.connection. lettus. LettuceClientConfigurationをインポートします。org.springframework.data.redis.connection. lettus. LettuceConnectionFactoryをインポートします。org.springframework.data.redis.core.RedisTemplateをインポートします。@ 設定
public class RedisConfig {
    @Bean
    パブリックRedisConnectionFactory redisConnectionFactory() {
        文字列ホスト="r-2zee50zxi5iiqm **** .redis.rds-aliyun.rds.aliyuncs.com";
        int port = 6379;
        文字列user = "default";
        文字列パスワード="Pas *** 23";
        文字列trustStoreFilePath = "/root/ApsaraDB-CA-Chain.jks";

        ClientOptions clientOptions = ClientOptions.builder().sslOptions ()
            SslOptions.builder().jdkSslProvider().truststore(new File(trustStoreFilePath)).build()).build();

        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        clusterConfiguration.clusterNode (ホスト、ポート);
        clusterConfiguration.setUsername (ユーザー);
        clusterConfiguration.setPassword (パスワード);

        LettuceClientConfiguration=lettuceClientConfiguration. builder()
            . clientOptions(clientOptions)
            . useSsl()
            . disablePeerVerification()
            .build();
        新しいLettuceConnectionFactory(clusterConfiguration, lettuceClientConfiguration) を返します。
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplateを返します。
    }
}

レタス

レタス6.3.0.RELEASEクライアントは、次のサンプルコードで使用されています。 クライアントの最新バージョンを使用することを推奨します。

import java.io.File;
import java.time.Duration;

import io.lettuce.core.RedisURI;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.SocketOptions.KeepAliveOptions;
import io.lettuce.core.SocketOptions.TcpUserTimeoutOptions;
import io.lettuce.core.SslOptions;
import io.lettuce.core.SslVerifyMode;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;

public class SSLClusterExample {
    /**
     * Enable TCP keepalive and add the following configurations:
     *  TCP_KEEPIDLE = 30
     *  TCP_KEEPINTVL = 10
     *  TCP_KEEPCNT = 3
     */
    private static final int TCP_KEEPALIVE_IDLE = 30;

    /**
     * You can use the TCP_USER_TIMEOUT parameter to prevent Lettuce from being stuck in a continuous timeout loop during a failure or crash event.
     * refer: https://github.com/lettuce-io/lettuce-core/issues/2082
     */
    private static final int TCP_USER_TIMEOUT = 30;

    public static void main(String[] args) throws Exception {
        String host = "r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com";
        int port = 6379;
        String password = "Pas***23";
        String trustStoreFilePath = "/root/ApsaraDB-CA-Chain.jks";

        RedisURI uri = RedisURI.builder()
            .withHost(host)
            .withPort(port)
            .withPassword(password.toCharArray())
            .withSsl(true)
            .withVerifyPeer(SslVerifyMode.CA) // SslVerifyMode.FULL cannot be used due to the unique nature of cluster instances in direct connection mode. Therefore, hostname verification must be skipped. 
            .build();

        SslOptions sslOptions = SslOptions.builder()
            .jdkSslProvider()
            .truststore(new File(trustStoreFilePath)).build();

        ClusterTopologyRefreshOptions refreshOptions = ClusterTopologyRefreshOptions.builder()
            .enablePeriodicRefresh(Duration.ofSeconds(15))
            .dynamicRefreshSources(false)
            .enableAllAdaptiveRefreshTriggers()
            .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(15)).build();

        // Config TCP KeepAlive
        SocketOptions socketOptions = SocketOptions.builder()
            .keepAlive(KeepAliveOptions.builder()
                .enable()
                .idle(Duration.ofSeconds(TCP_KEEPALIVE_IDLE))
                .interval(Duration.ofSeconds(TCP_KEEPALIVE_IDLE / 3))
                .count(3)
                .build())
            .tcpUserTimeout(TcpUserTimeoutOptions.builder()
                .enable()
                .tcpUserTimeout(Duration.ofSeconds(TCP_USER_TIMEOUT))
                .build())
            .build();

        RedisClusterClient redisClient = RedisClusterClient.create(uri);
        redisClient.setOptions(ClusterClientOptions.builder()
            .socketOptions(socketOptions)
            .sslOptions(sslOptions)
            .validateClusterNodeMembership(false)
            .topologyRefreshOptions(refreshOptions).build());

        StatefulRedisClusterConnection<String, String> connection = redisClient.connect();
        connection.sync().set("key", "value");
        System.out.println(connection.sync().get("key"));
    }
}

行く

go-redis 9.5.1クライアントは、次のサンプルコードで使用されています。 go-redis 9.0以降の使用を推奨します。

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"crypto/tls"
	"crypto/x509"
	"github.com/redis/go-redis/v9"
)

var ctx = context.Background()

func main() {
        caCert, err := ioutil.ReadFile("/root/ApsaraDB-CA-Chain.pem")
	if err != nil {
		fmt.Println("Error loading CA certificate:", err)
		return
	}

	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	tlsConfig := &tls.Config{
		RootCAs:            caCertPool,
		InsecureSkipVerify: true, // Not actually skipping, we check the cert in VerifyPeerCertificate
		VerifyPeerCertificate: func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
			// Code copy/pasted and adapted from
			// https://github.com/golang/go/blob/81555cb4f3521b53f9de4ce15f64b77cc9df61b9/src/crypto/tls/handshake_client.go#L327-L344, but adapted to skip the hostname verification.
			// See https://github.com/golang/go/issues/21971#issuecomment-412836078.

			// If this is the first handshake on a connection, process and
			// (optionally) verify the server's certificates.
			certs := make([]*x509.Certificate, len(rawCerts))
			for i, asn1Data := range rawCerts {
				cert, err := x509.ParseCertificate(asn1Data)
				if err != nil {
					panic(err)
				}
				certs[i] = cert
			}

			opts := x509.VerifyOptions{
				Roots:         caCertPool,
				DNSName:       "", // <- skip hostname verification
				Intermediates: x509.NewCertPool(),
			}

			for i, cert := range certs {
				if i == 0 {
					continue
				}
				opts.Intermediates.AddCert(cert)
			}
			_, err := certs[0].Verify(opts)
			return err
		},
	}

	rdb := redis.NewClusterClient(&redis.ClusterOptions{
		Addrs:    []string{"r-2zee50zxi5iiqm****.redis.rds-aliyun.rds.aliyuncs.com:6379"},
		Username: "default",
		Password: "Pas***23",
		TLSConfig: tlsConfig,
	})

	err = rdb.Set(ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := rdb.Get(ctx, "key").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("key:", val)
}

よくある質問

  • No subject alternative DNS name matching xxx foundエラーが返されるのはなぜですか?

    インスタンスのTLSを有効にした後、インスタンスのエンドポイントまたはポート番号を変更し、TLSを使用してインスタンスに接続すると、前述のエラーが発生します。 コンソールでTLS証明書を更新して、もう一度お試しください。