The ApsaraDB for Redis service is compatible with native Redis databases. Therefore, you can connect to both database services in similar ways. All clients that are compatible with the Redis protocols support connections to ApsaraDB for Redis. You can use any of these clients that are suitable for your applications. You can connect to an ApsaraDB for Redis instance by using clients for different programming languages.

Prerequisites

Perform the following operations based on the deployment location of the client application:
Client application deployment location Operations
ECS instance (Recommended)
  1. Make sure that the ECS instance and the ApsaraDB for Redis instance belong to the same virtual private cloud (VPC). They have the same VPC ID in the Basic Information section.
    Note If they 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.
  2. Obtain the internal IP address of an ECS instance. For more information, see How do I query 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 Set IP address whitelists.
On-premises machine
  1. By default, an ApsaraDB for Redis instance provides only an internal endpoint. You must apply for a public endpoint when you want to connect to an ApsaraDB for Redis instance over the Internet. 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 the on-premises host where the client application is deployed to obtain the public IP address of the on-premises machine. The returned result is shown in the following figure.View public IP address results
    Note If the on-premises machine runs a Windows operating system, you can visit ipinfo to get the public IP address.
  3. Add the public endpoint of the on-premises machine to the whitelist of the ApsaraDB for Redis instance. For more information, see Set IP address whitelists.

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 as 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 in VPC is enabled for an instance, the client in the same VPC can connect to the ApsaraDB for Redis instance without the required password.

Obtain connection information

When you use a client to connect to an ApsaraDB for Redis instance, you must obtain the following information and set it in the code:

Information Method
Instance endpoint Redis instances support multiple types of connection endpoints. We recommend that you use private 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 also use a custom port number. For more information, see Modify the port for the endpoint.
The account of the instance. This parameter is not required by some clients. By default, an ApsaraDB for Redis instance contains a database account named after the instance ID, for example, r-bp10noxlhcoim2****. You can also create an account and grant required permissions. For more information, see Manage database accounts.
The password of the account.

The password format is different 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, the password is testaccount:Rp829dlwa.
Note If you forget your password, see Change or reset the password.

Common client applications

For a list of clients supported by Redis, see Redis clients.

Jedis client

  1. Download and install the Jedis client. For more information, see Jedis.
  2. Select a connection method based on your business requirements.
    • JedisPool-based connection. This method is recommended.
      1. Launch the Eclipse client, create a project, and then configure the following pom file:
        <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.7.2</version>
        <type>jar</type>
        <scope>compile</scope>
        </dependency>
      2. Enter the following code in the project to add the related application.
        import org.apache.commons.pool2.PooledObject;
        import org.apache.commons.pool2.PooledObjectFactory;
        import org.apache.commons.pool2.impl.DefaultPooledObject;
        import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
        import redis.clients.jedis.HostAndPort;
        import redis.clients.jedis.Jedis;
        import redis.clients.jedis.JedisPool;
        import redis.clients.jedis.JedisPoolConfig;
      3. Enter the following code in the project based on the Jedis client version, and then modify the code based on the comments.
        Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
        • Jedis 2.7.2
          JedisPoolConfig config = new JedisPoolConfig();
          //Maximum number of idle connections. You can customize this parameter. Make sure that the specified maximum number of idle connections does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports.
          config.setMaxIdle(200);
          //Maximum number of connections. You can customize this parameter. Make sure that the specified maximum number of connections does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports.
          config.setMaxTotal(300);
          config.setTestOnBorrow(false);
          config.setTestOnReturn(false);
          String host = "*.aliyuncs.com";
          String password = "Password";
          JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
          Jedis jedis = null;
          try {
          jedis = pool.getResource();
          /// ... do stuff here ... for example
          jedis.set("foo", "bar");
          String foobar = jedis.get("foo");
          jedis.zadd("sose", 0, "car");
          jedis.zadd("sose", 0, "bike");
          Set<String> sose = jedis.zrange("sose", 0, -1);
          } finally {
          if (jedis ! = null) {
          jedis.close();
          }
          }
          /// ... when closing your application:
          pool.destroy();
        • Jedis 2.6 or Jedis 2.5
          JedisPoolConfig config = new JedisPoolConfig();
          //Maximum number of idle connections. You can customize this parameter. Make sure that the specified maximum number of idle connections does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports.
          config.setMaxIdle(200);
          //Maximum number of connections. You can customize this parameter. Make sure that the specified maximum number of connections does not exceed the maximum number of connections that the ApsaraDB for Redis instance supports.
          config.setMaxTotal(300);
          config.setTestOnBorrow(false);
          config.setTestOnReturn(false);
          String host = "*.aliyuncs.com";
          String password = "Password";
          JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
          Jedis jedis = null;
          boolean broken = false;
          try {
               jedis = pool.getResource();
               /// ... do stuff here ... for example
               jedis.set("foo", "bar");
               String foobar = jedis.get("foo");
               jedis.zadd("sose", 0, "car");
               jedis.zadd("sose", 0, "bike");
               Set<String> sose = jedis.zrange("sose", 0, -1);
          } 
          catch(Exception e)
          {
               broken = true;
          } finally {
          if (broken) {
               pool.returnBrokenResource(jedis);
          } else if (jedis ! = null) {
               pool.returnResource(jedis);
           }
          }
    • Single Jedis connection. This method is not recommended because a client cannot automatically reconnect to the ApsaraDB for Redis instance after a connection times out.

      Launch the Eclipse client, create a project, enter the following code, and then modify the code based on the comments.

      Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
      import redis.clients.jedis.Jedis;
      public class jedistest {
      public static void main(String[] args) {
      try {
           String host = "xx.kvstore.aliyuncs.com";//You can find the connection address in the console.
           int port = 6379;
           Jedis jedis = new Jedis(host, port);
           //Authentication information.
           jedis.auth("password");//password
           String key = "redis";
           String value = "aliyun-redis";
           //Select a database. Default value: 0.
           jedis.select(1);
           //Set a key.
           jedis.set(key, value);
           System.out.println("Set Key " + key + " Value: " + value);
           //Obtain the configured key and value.
           String getvalue = jedis.get(key);
           System.out.println("Get Key " + key + " ReturnValue: " + getvalue);
           jedis.quit();
           jedis.close();
      } 
      catch (Exception e) {
       e.printStackTrace();
       }
      }
      }
  3. Run the project. If you see the following result in Eclipse, the client has connected to the ApsaraDB for Redis instance.
    Set Key redis Value aliyun-redis
    Get Key redis ReturnValue aliyun-redis
Warning If some invalid parameters are set or some features are improperly used, errors may be reported. For more information about how to troubleshoot errors, see Jedis common exceptions.

Lettuce client

A Lettuce client supports synchronous and asynchronous communication based on comprehensive Redis API operations. A Lettuce client does not automatically reconnect to an instance after multiple requests time out. If failures occur in ApsaraDB for Redis and cause failovers for proxy servers or database nodes, a connection timeout may occur. This may result in the failure to reconnect to ApsaraDB for Redis. To avoid such risks, we recommend that you use Jedis client.

Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.

For more information, see Lettuce.

TairJedis client

TairJedis is an ApsaraDB for Redis client developed by Alibaba Cloud. TairJedis supports the features of Jedis and features dedicated for ApsaraDB for Redis Enhanced Edition (Tair). For example, TairJedis supports the Tair structures and Tair commands.

Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.

For more information, see tairjedis-sdk.

PhpRedis client

  1. Download and install the phpredis client. For more information, see phpredis.
  2. Enter the following code in a PHP editor and modify the code as required based on comments.
    Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
    <? php
     /* Replace the parameter values with the address and port number of the instance. */
     $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
     $port = 6379;
     /* Replace the parameter values with the ID and password of the instance. */
     $user = "test_username";
     $pwd = "test_password";
     $redis = new Redis();
     if ($redis->connect($host, $port) == false) {
             die($redis->getLastError());
       }
     if ($redis->auth($pwd) == false) {
             die($redis->getLastError());
      }
      /* You can perform database operations after authentication. For more information, visit https://github.com/phpRedis/phpredis. */.
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     $value = $redis->get("foo");
     echo $value;
     ? >
  3. The client can connect to the ApsaraDB for Redis instance after the preceding code is run.
    For more information, see phpredis.

Redis-py client

  1. Download and install the redis-py client. For more information, see redis-py.
  2. Enter the following code in a Python editor and modify the code as required based on comments.
    Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
    #! /usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    #Replace the following parameter values with the host name and port number of the instance.
    host = 'localhost'
    port = 6379
    #Replace the following parameter value with the password of the instance.
    pwd = 'test_password'
    r = redis.StrictRedis(host=host, port=port, password=pwd)
    #You can perform database operations after you establish a connection. For more information, visit https://github.com/andymccurdy/redis-py.
    r.set('foo', 'bar');
    print r.get('foo')
  3. The client can connect to the ApsaraDB for Redis instance after the preceding code is run.

C or C++ client

  1. Run the following command to download, compile, and install the C client.
    git clone https://github.com/redis/hiredis.git
    cd hiredis
    make
    sudo make install
  2. Enter the following code in a C or C ++ editor and modify the code as required based on comments.
    Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <hiredis.h>
    int main(int argc, char **argv) {
    unsigned int j;
    redisContext *c;
    redisReply *reply;
    if (argc < 4) {
            printf("Usage: example xxx.kvstore.aliyuncs.com 6379 instance_id password\n");
            exit(0);
    }
    const char *hostname = argv[1];
    const int port = atoi(argv[2]);
    const char *instance_id = argv[3];
    const char *password = argv[4];
    struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    c = redisConnectWithTimeout(hostname, port, timeout);
    if (c == NULL || c->err) {
    if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
    } else {
            printf("Connection error: can't allocate redis context\n");
    }
    exit(1);
    }
    /* AUTH */
    reply = redisCommand(c, "AUTH %s", password);
    printf("AUTH: %s\n", reply->str);
    freeReplyObject(reply);
    /* PING server */
    reply = redisCommand(c,"PING");
    printf("PING: %s\n", reply->str);
    freeReplyObject(reply);
    /* Set a key */
    reply = redisCommand(c,"SET %s %s", "foo", "hello world");
    printf("SET: %s\n", reply->str);
    freeReplyObject(reply);
    /* Set a key using binary safe API */
    reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
    printf("SET (binary API): %s\n", reply->str);
    freeReplyObject(reply);
    /* Try a GET and two INCR */
    reply = redisCommand(c,"GET foo");
    printf("GET foo: %s\n", reply->str);
    freeReplyObject(reply);
    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);
    /* again ... */
    reply = redisCommand(c,"INCR counter");
    printf("INCR counter: %lld\n", reply->integer);
    freeReplyObject(reply);
    /* Create a list of numbers, from 0 to 9 */
    reply = redisCommand(c,"DEL mylist");
    freeReplyObject(reply);
    for (j = 0; j < 10; j++) {
            char buf[64];
            snprintf(buf,64,"%d",j);
            reply = redisCommand(c,"LPUSH mylist element-%s", buf);
            freeReplyObject(reply);
        }
    /* Let's check what we have inside the list */
    reply = redisCommand(c,"LRANGE mylist 0 -1");
    if (reply->type == REDIS_REPLY_ARRAY) {
            for (j = 0; j < reply->elements; j++) {
            printf("%u) %s\n", j, reply->element[j]->str);
    }
    }
    freeReplyObject(reply);
    /* Disconnects and frees the context */
    redisFree(c);
    return 0;
    }
  3. Compile the code.
    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. Perform a test run and connect to the ApsaraDB for Redis instance.
     example xxx.kvstore.aliyuncs.com 6379 instance_id password

.NET client

Warning If you need to switch or select a database from multiple databases in a cluster instance or read/write splitting instance, you must set the cluster_compat_enable parameter to 0. This disables the support of the native Redis cluster syntax. Otherwise, the system sends an error message: Multiple databases are not supported on this server; cannot switch to database. For more information, see Parameter overview and configuration guide.
  1. Run the following command to download the .NET client.
     git clone https://github.com/ServiceStack/ServiceStack.Redis
  2. Create a .NET project on the .NET client.
  3. Add the reference file stored in the library file directory ServiceStack.Redis/lib/tests to the client.
  4. Enter the following code in the .NET project and modify the code as required based on comments. For more information, see ServiceStack.Redis.
    Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
    using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
     using System.Threading.Tasks;
     using ServiceStack.Redis;
     namespace ServiceStack.Redis.Tests
     {
             class Program
     {
     public static void RedisClientTest()
     {
             string host = "127.0.0.1";/*The IP address of the host*/
             string password = "password";/*Password*/
             RedisClient redisClient = new RedisClient(host, 6379, password);
             string key = "test-aliyun";
             string value = "test-aliyun-value";
             redisClient.Set(key, value);
             string listKey = "test-aliyun-list";
             System.Console.WriteLine("set key " + key + " value " + value);
             string getValue = System.Text.Encoding.Default.GetString(redisClient.Get(key));
             System.Console.WriteLine("get key " + getValue);
             System.Console.Read();
     }
     public static void RedisPoolClientTest()
     {
             string[] testReadWriteHosts = new[] {
             "redis://password@127.0.0.1:6379"/*redis://Password@IP address:port*/
     };
     RedisConfig.VerifyMasterConnections = false;//Required.
     PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*Number of connection pools*/, 10/*Connection pool timeout value*/, testReadWriteHosts);
     for (int i = 0; i < 100; i++){
             IRedisClient redisClient = redisPoolManager.GetClient();//Obtain the connection.
             RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient;
             redisNativeClient.Client = null;//ApsaraDB for Redis does not support the CLIENT SETNAME command. Set Client to null.
     try
     {
             string key = "test-aliyun1111";
             string value = "test-aliyun-value1111";
             redisClient.Set(key, value);
             string listKey = "test-aliyun-list";
             redisClient.AddItemToList(listKey, value);
             System.Console.WriteLine("set key " + key + " value " + value);
             string getValue = redisClient.GetValue(key);
             System.Console.WriteLine("get key " + getValue);
             redisClient.Dispose();//
     }catch (Exception e)
     {
             System.Console.WriteLine(e.Message);
     }
     }
             System.Console.Read();
     }
     static void Main(string[] args)
     {
             //Single-connection mode.
             RedisClientTest();
             //Connection-pool mode.
             RedisPoolClientTest();
     }
     }
     }

node-redis client

  1. Download and install the node-redis client.
    npm install hiredis redis
  2. Enter the following code in the node-redis client and modify the code as required based on comments.
    Note For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
     var redis = require("redis"),
     client = redis.createClient(<port>, <"host">, {detect_buffers: true});
     client.auth("password", redis.print)

    Parameters:

    • <port>: the service port number of the ApsaraDB for Redis database. The default port number is 6379.
    • <"host">: the connection address of the ApsaraDB for Redis instance.

    Configuration examples:

    var redis = require("redis"),
    client = redis.createClient(6379, "r-abcdefg.redis.rds.aliyuncs.com", {detect_buffers: true});
    client.auth("password", redis.print)
  3. Execute the preceding code to connect to the ApsaraDB for Redis instance.
  4. Use ApsaraDB for Redis.
    // Write data to the ApsaraDB for Redis instance.
     client.set("key", "OK");
     // Query data on the ApsaraDB for Redis instance. The data of the String type is returned.
     client.get("key", function (err, reply) {
     console.log(reply.toString()); // print `OK`
     });
     // If the input parameter is a buffer, the returned value is also a buffer.
     client.get(new Buffer("key"), function (err, reply) {
     console.log(reply.toString()); // print `<Buffer 4f 4b>`
     });
     client.quit();

C# client StackExchange.Redis

Warning If you need to switch or select a database from multiple databases in a cluster instance or read/write splitting instance, you must set the cluster_compat_enable parameter to 0. This disables the support of the native Redis cluster syntax. Otherwise, the system sends an error message: RedisCommandException: Multiple databases are not supported on this server; cannot switch to database: 1. For more information, see Parameter overview and configuration guide.
  1. Download and install the StackExchange.Redis client.
  2. Add a reference.
    using StackExchange.Redis;
  3. Initialize ConnectionMultiplexer.

    ConnectionMultiplexer is the core of StackExchange.Redis. It is shared and reused in the entire application. You must use ConnectionMultiplexer as a singleton. ConnectionMultiplexer is initialized in the following way:

    Note
    • For more information about how to obtain the connection endpoint and password of the ApsaraDB for Redis instance, see Obtain connection information.
    • ConfigurationOptions contains multiple options, such as keepAlive, connectRetry, and name. For more information, see ConfigurationOptions.
     // redis config
     private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("127.0.0.1:6379,password=xxx,connectTimeout=2000");
      //the lock for singleton
     private static readonly object Locker = new object();
      //singleton
     private static ConnectionMultiplexer redisConn;
     //singleton
     public static ConnectionMultiplexer getRedisConn()
     {
         if (redisConn == null)
         {
             lock (Locker)
             {
                 if (redisConn == null || ! redisConn.IsConnected)
                 {
                     redisConn = ConnectionMultiplexer.Connect(configurationOptions);
                 }
             }
         }
         return redisConn;
     }
  4. GetDatabase() returns a lightweight object. You can obtain this object from the object of ConnectionMultiplexer.
     redisConn = getRedisConn();
     var db = redisConn.GetDatabase();
  5. You can use the client to perform database operations.
    Note The following table describes the demo examples of command operations for general data types, which are slightly different from the native Redis commands.
    • String
      //set get
      string strKey = "hello";
      string strValue = "world";
      bool setResult = db.StringSet(strKey, strValue);
      Console.WriteLine("set " + strKey + " " + strValue + ", result is " + setResult);
      //incr
      string counterKey = "counter";
      long counterValue = db.StringIncrement(counterKey);
      Console.WriteLine("incr " + counterKey + ", result is " + counterValue);
      //expire
      db.KeyExpire(strKey, new TimeSpan(0, 0, 5));
      Thread.Sleep(5 * 1000);
      Console.WriteLine("expire " + strKey + ", after 5 seconds, value is " + db.StringGet(strKey));
      //mset mget
      KeyValuePair<RedisKey, RedisValue> kv1 = new KeyValuePair<RedisKey, RedisValue>("key1", "value1");
      KeyValuePair<RedisKey, RedisValue> kv2 = new KeyValuePair<RedisKey, RedisValue>("key2", "value2");
      db.StringSet(new KeyValuePair<RedisKey, RedisValue>[] {kv1,kv2});            
      RedisValue[] values = db.StringGet(new RedisKey[] {kv1.Key, kv2.Key});
      Console.WriteLine("mget " + kv1.Key.ToString() + " " + kv2.Key.ToString() + ", result is " + values[0] + "&&" + values[1]);
    • Hash
      string hashKey = "myhash";
      //hset
      db.HashSet(hashKey,"f1","v1");
      db.HashSet(hashKey,"f2", "v2");
      HashEntry[] values = db.HashGetAll(hashKey);
      //hgetall
      Console.Write("hgetall " + hashKey + ", result is");
      for (int i = 0; i < values.Length;i++) 
      {
        HashEntry hashEntry = values[i];
        Console.Write(" " + hashEntry.Name.ToString() + " " + hashEntry.Value.ToString());
      }
      Console.WriteLine();
    • List
      //list key
      string listKey = "myList";
      //rpush
      db.ListRightPush(listKey, "a");
      db.ListRightPush(listKey, "b");
      db.ListRightPush(listKey, "c");
      //lrange
      RedisValue[] values = db.ListRange(listKey, 0, -1);
      Console.Write("lrange " + listKey + " 0 -1, result is ");
      for (int i = 0; i < values.Length; i++)
      {
       Console.Write(values[i] + " ");
      }
      Console.WriteLine();
    • Set
      //set key
      string setKey = "mySet";
      //sadd
      db.SetAdd(setKey, "a");
      db.SetAdd(setKey, "b");
      db.SetAdd(setKey, "c");
      //sismember
      bool isContains = db.SetContains(setKey, "a");
      Console.WriteLine("set " + setKey + " contains a is " + isContains );
    • Sorted Set
      string sortedSetKey = "myZset";
      //sadd
      db.SortedSetAdd(sortedSetKey, "xiaoming", 85);
      db.SortedSetAdd(sortedSetKey, "xiaohong", 100);
      db.SortedSetAdd(sortedSetKey, "xiaofei", 62);
      db.SortedSetAdd(sortedSetKey, "xiaotang", 73);
      //zrevrangebyscore
      RedisValue[] names = db.SortedSetRangeByRank(sortedSetKey, 0, 2, Order.Ascending);
      Console.Write("zrevrangebyscore " + sortedSetKey + " 0 2, result is ");
      for (int i = 0; i < names.Length; i++)
      {
        Console.Write(names[i] + " ");
      }
      Console.WriteLine();