When you connect to an ApsaraDB for Redis instance by using a client, you can enable the SSL encryption feature to enhance the security of data links and ensure data integrity. You can use a client that is compatible with the Redis protocol to connect to an ApsaraDB for Redis instance. You can use a variety of clients of different programming languages to connect to an ApsaraDB for Redis instance. 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 for an ApsaraDB for Redis instance.

Precautions

  • By default, cluster or read/write splitting instances use the proxy mode. In this mode, you can access ApsaraDB for Redis instances by using the endpoint of the proxy server in the same way that you access standard instances of ApsaraDB for Redis.
    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.
  • If password-free access for VPCs is enabled for an instance, the client in the same VPC can connect to the ApsaraDB for Redis instance without the password.

Preparations

  1. Perform the following operations based on the type of host on which a client is deployed.
    Host on which the client is deployed Operation
    ECS instance (recommended)
    1. Make sure that the ECS instance and the ApsaraDB for Redis instance belong to the same virtual private cloud (VPC). The instances display the same VPC ID in the Basic Information section.
      Note
      • If the ECS 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 are different. For example, the ECS instance belongs to a classic network and the ApsaraDB for Redis instance belongs to a VPC. For more information about how to connect to an ApsaraDB for Redis instance from an ECS instance when the instances are deployed in different network types, 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 How do I query the IP addresses of ECS instances?
    3. Add the internal IP address of the ECS instance to the whitelist of the ApsaraDB for Redis instance. For more information, see Configure whitelists.
    On-premises machine
    1. By default, an ApsaraDB for Redis instance provides only an internal endpoint. 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.
    2. Run the curl ipinfo.io |grep ip command on the on-premises machine on which the client is deployed to obtain the public IP address of the on-premises machine. The returned result is shown in the following figure.View the public IP address of the on-premises machine
      Note If the on-premises machine runs a Windows operating system, go to ipinfo to obtain the public IP address.
    3. Add the public IP address of the on-premises machine to the 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.
    Information Description
    Instance endpoint ApsaraDB for Redis instances support multiple types of endpoints. We recommend that you use internal endpoints in a VPC for higher security and lower network latency. For more information, see View endpoints.
    Port number The default port number is 6379. You can use a custom port number. For more information, see Change the endpoint or port number of an ApsaraDB for Redis instance.
    Instance account (this parameter is not required by some clients) By default, an ApsaraDB for Redis instance contains a database account that is named after the instance ID, for example, r-bp10noxlhcoim2****. You can create an account and grant required permissions. For more information, see Create and manage database accounts.
    Password

    The password format varies based on the selected account:

    • Default account (the account named after the instance ID): Directly enter the password.
    • New account: The format of the password must be <user>:<password>. For example, if the username of a custom account is testaccount and the password is Rp829dlwa, you must enter testaccount:Rp829dlwa.
    Note If you forget your password, see Change or reset the password.
  3. Download the CA certificate. For more information, see Configure SSL encryption for an ApsaraDB for Redis instance.

Java

The following sample code uses Jedis 3.6.0. We recommend that you use the latest version.

Note You must modify your code based on comments. For more 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.
        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.

Note You must modify your code based on comments. For more 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, password with the endpoint, port number, and password of the instance.
#ApsaraDB-CA-Chain.pem is the name of the CA certificate.
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, password with the endpoint, port number, and password of the instance.
#ApsaraDB-CA-Chain.pem is the name of the CA certificate.
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. If you use the phpredis client, you can reference SSL/TLS with certification file to connect to an instance.

Note You must modify your code based on comments. For more 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, 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: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";

?>