When you connect to a Tair instance by using a client, you can enable the SSL encryption feature to enhance data security 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 describes how to connect to a Tair instance by using clients of different programming languages.
Prerequisites
SSL encryption is enabled for your Tair instance. For more information, see Configure SSL 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
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
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.
Obtain the following information and use the information in client code of different programming languages.
Information
Method to obtain the information
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 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, you can enter only the password.
If you use a custom account, the password of the account must be 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 istestaccount
and the password isRp829dlwa
, entertestaccount:Rp829dlwa
as the password.
NoteIf you use a management tool such as Redis Desktop Manager (RDM) to connect to the Tair instance, enter a password in the
<user>:<password>
format.If you forget your password, you can reset it. For more information, see Change or reset the password.
Download the certificate authority (CA) certificate. For more information, see Configure SSL encryption.
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.
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, 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")
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, 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")
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, 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 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, 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"));
}
}
}
}