When you connect to an ApsaraDB for Redis instance by using a client, you can enable the SSL encryption feature to enhance data security and ensure data integrity. You can connect to an ApsaraDB for Redis instance by using clients of different programming languages that are compatible with the Redis protocol. This topic describes sample code of common programming languages.

Prerequisites

SSL encryption is enabled for an ApsaraDB for Redis instance. For more information, see Configure SSL encryption.

Precautions

  • By default, cluster or read/write splitting instances use the proxy mode. In this mode, you can access an ApsaraDB for Redis instance by using the endpoint of a proxy node in the instance in the same way that you access an ApsaraDB for Redis standard instance. For more information about cluster instances and read/write splitting instances, see Cluster master-replica instances or Read/write splitting instances.
    Note If you use a private endpoint to connect to an ApsaraDB for Redis instance, you can connect to the instance in the same way that you connect to an open source Redis cluster. For more information about private endpoints, see Enable the direct connection mode.
  • If password-free access is enabled for an ApsaraDB for Redis instance deployed in a VPC, a client in the same VPC as the instance can connect to the instance without using passwords. For more information, see Enable password-free access.

Preparations

  1. Perform the following operations based on the type of host on which a client is deployed.
    Host Operation
    ECS instance (recommended)
    1. Make sure that the Elastic Compute Service (ECS) instance and the ApsaraDB for Redis instance belong to the same virtual private cloud (VPC). In this case, the same VPC ID is displayed in the Basic Information section of the instances.
      Note
      • If the instances are deployed in different VPCs, you can change the VPC to which the ECS instance belongs. For more information, see Change the VPC of an ECS instance.
      • The network types of the ECS instance and the ApsaraDB for Redis instance may be different. For example, the ECS instance belongs to the classic network and the ApsaraDB for Redis instance belongs to a VPC. For information about how to connect to an ApsaraDB for Redis instance from an ECS instance when the instances are deployed in different types of networks, see Connect an ECS instance to an ApsaraDB for Redis instance in different types of networks.
    2. Obtain the internal IP address of the ECS instance. For more information, see Network FAQ.
    3. Add the internal IP address of the ECS instance to a whitelist of the ApsaraDB for Redis instance. For more information, see Configure whitelists.
    On-premises device
    1. By default, only internal endpoints are available for ApsaraDB for Redis instances. If you want to connect to an ApsaraDB for Redis instance over the Internet, you must apply for a public endpoint. For more information, see Apply for a public endpoint for an ApsaraDB for Redis instance.
    2. Run the curl ipinfo.io |grep ip command on your on-premises device to obtain its public IP address. The following figure shows an example command output.View the public IP address of your on-premises device
      Note If your on-premises device runs a Windows operating system, visit ipinfo to obtain the public IP address.
    3. Add the public IP address of your on-premises device to a whitelist of the ApsaraDB for Redis instance. For more information, see Configure whitelists.
  2. Obtain the following information and use the information in client code of different programming languages.
    Item Description
    Instance endpoint ApsaraDB for Redis instances support multiple endpoint types. We recommend that you use VPCs for higher security and lower network latency. For more information, see View endpoints.
    Port number The default port number is 6379. You can also use a custom port number. For more information, see Change the endpoint or port number of an ApsaraDB for Redis instance.
    Instance account (this information is optional for specific clients) By default, an ApsaraDB for Redis instance has a database account that is named after the instance ID. Example: r-bp10noxlhcoim2****. You can create another database account and grant the required permissions to the account. For more information, see Create and manage database accounts.
    Password

    The password format varies based on the selected account:

    • If you use the default account whose username is the same as the instance ID, enter only the password.
    • If you use a custom account, enter a password in the format of <user>:<password>. For example, if the username of the custom account is testaccount and the password is Rp829dlwa, you must enter testaccount:Rp829dlwa as the database password.
    Note
    • If you use a management tool such as Redis Desktop Manager (RDM) to connect to the ApsaraDB for Redis instance, enter a password in the format of <user>:<password>.
    • If you forget your password, you can reset it. For more information, see Change or reset the password.
  3. Download the certificate authority (CA) certificate. For more information, see Configure SSL encryption.

Java

The following sample code uses the Jedis 3.6.0 client. We recommend that you use the latest version of the client. For more information, visit Jedis.

Note You must modify your code based on comments. For information about how to obtain the endpoint, port number, and password of an ApsaraDB for Redis instance, see Step 2 of the Preparations section.
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:Test1234", 0, true, sslSocketFactory, null, null);

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

Python

The following sample code uses the redis-py client. We recommend that you use the latest version of the client. For more information, visit redis-py.

Note You must modify your code based on comments. For information about how to obtain the endpoint, port number, and password of an ApsaraDB for Redis instance, see Step 2 of the Preparations section.
#!/bin/python
import redis

# Specify connection information. Replace the values of host, port, and password with the endpoint, port number, and password of the instance, respectively. 
# ApsaraDB-CA-Chain.pem is the name of the CA certificate file. 
client = redis.Redis(host="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")
#!/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, respectively. 
# 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:Test1234",
                            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")

PHP

The following sample code uses the Predis client. We recommend that you use the latest version of the client. For more information, visit Predis. If you use the PhpRedis client, you can reference SSL/TLS with certification file to connect to an instance. For more information about PhpRedis, visit PhpRedis.

Note You must modify your code based on comments. For information about how to obtain the endpoint, port number, and password of an ApsaraDB for Redis instance, see Step 2 of the Preparations section.
<?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, respectively.
ApsaraDB-CA-Chain.pem is the name of the CA certificate file. */
$client = new Predis\Client([
    'scheme' => 'tls',
    'host'   => 'r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com',
    'port'   => 6379,
    'password' => 'redistest:Test1234',
    '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#

The following sample code uses the StackExchange.Redis client. We recommend that you use the latest version of the client. For more information, visit StackExchange.Redis.

Note You must modify your code based on comments. For information about how to obtain the endpoint, port number, and password of an ApsaraDB for Redis instance, see Step 2 of the Preparations section.
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, respectively. 
          // 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:Test1234",
                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"));
            }
        }
    }
}