All Products
Search
Document Center

Tair:Use a client to connect to a Tair instance that has TLS (SSL) encryption enabled

Last Updated:Feb 21, 2024

When you connect to a Tair instance by using a client, you can enable the TLS (SSL) encryption feature to enhance the security of data links and ensure data integrity. You can connect to a Tair instance by using clients of different programming languages that are compatible with the Tair protocol. This topic provides sample code on how to connect to a Tair instance by using common clients.

Prerequisites

  • TLS (SSL) encryption is enabled for your Tair instance. For more information, see Enable TLS encryption.

  • The client is hosted on an Elastic Compute Service (ECS) instance that resides in the same virtual private cloud (VPC) as the Tair instance.

Usage notes

  • After you enable Transport Layer Security (TLS) encryption for your instance, your client can connect to the instance only over a VPC.

  • By default, cluster or read/write splitting instances run in proxy mode. In this mode, you can connect to a Tair instance by using the endpoint of a proxy node in the instance in the same manner as you connect to a standard instance. For more information about cluster and read/write splitting instances, see Cluster architecture and Read/write splitting architecture.

  • If password-free access is enabled for an instance deployed in a VPC, clients within the same VPC as the instance can access the instance without using passwords.

Preparations

  1. Add the internal IP address of the ECS instance that hosts the client to a whitelist of the Tair 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

    Tair instances support multiple endpoint types. We recommend that you use VPCs for higher security and lower network latency. For more information, see View endpoints and port numbers.

    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 a Tair instance.

    Instance account (optional for specific clients)

    By default, a Tair 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, directly enter the password.

    • If you use a custom account, enter the password in the <user>:<password> format. A password in this format can also be used for default account logon. For example, if the username of the custom account is testaccount and the password is Rp829dlwa, enter testaccount:Rp829dlwa as the password.

    Note
    • If you use a management tool such as Redis Desktop Manager (RDM) to connect to the Tair instance, enter the password in the <user>:<password> format.

    • If you forget your password, reset it. For more information, see Change or reset the password.

  3. Download the certification authority (CA) certificate. For more information, see Enable TLS encryption.

redis-cli

Before you can enable TLS encryption for your Tair instance in redis-cli, you must set BUILD_TLS to yes when you compile open source Redis.

  1. Log on to the ECS instance. Then, download and install redis-cli.

    1. Run the following command to install the required dependencies:

      yum install openssl-devel gcc
    2. Run the following command to download the Redis source code package.

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

      In this example, Redis 7.0.0 is used to demonstrate the operations. You can install other versions. For more information, visit the Redis official website.

    3. Run the following command to decompress the Redis source code package.

      tar xzf redis-7.0.0.tar.gz
    4. Run the following command to go to the directory to which the source code package of open source Redis is decompressed. Compile and install the source code, and then set BUILD_TLS to yes.

      cd redis-7.0.0&&make BUILD_TLS=yes

      It takes 2 or 3 minutes to compile and install open source Redis.

  2. Run the following command in redis-cli to connect to your instance:

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

    You must specify the path of the CA certificate in the wake of cacert.

  3. Run the following command to verify the password:

    AUTH password

    If the instance is connected by using redis-cli, OK is displayed.

Java

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

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 redis-py client is used in the following sample code. We recommend that you use the latest version of the client.

Connections from a connection pool

#!/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: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")

Regular connections

#!/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. 
# 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")

PHP

The Predis client is used in the following sample code. We recommend that you use the latest version of the client. If you use the PhpRedis client, you can refer to SSL/TLS with certification file to connect to an instance.

<?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: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 StackExchange.Redis client is used in the following sample code. We recommend that you use the latest version of the client.

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: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"));
            }
        }
    }
}

Spring Data Redis

The Spring Data Redis 2.7.12 client that is compatible with Java 1.8 is used in the following sample code. We recommend that you use the latest version of the client.

@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 = "xxx";
        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<>();
    }
}

Lettuce

The Lettuce 6.2.4.RELEASE client is used in the following sample code. We recommend that you use the latest version of the client.

public class SSLExample {
    public static void main(String[] args) throws Exception {
        String host = "r-bp1zxszhcgatnx****.redis.rds.aliyuncs.com";
        int port = 6379;
        String password = "xxxx";
        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"));

    }
}