ApsaraDB for Redis is fully compatible with open source Redis. You can connect to an ApsaraDB for Redis instance in the same way as you connect to open source Redis. Therefore, you can use a client that is compatible with the Redis protocol to connect to an ApsaraDB for Redis instance. You can connect to an ApsaraDB for Redis instance by using clients of different programming languages.

Prerequisites

The operations listed in the following table are performed based on the type of host on which the 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). If the VPC IDs of these two instances are the same, the instances belong to the same VPC.
    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 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 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 a sample 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.

Precautions

  • By default, cluster or read/write splitting instances run in 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 as you access an ApsaraDB for Redis standard instance. For more information about cluster 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 as 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.

Obtain connection information

When you use a client to connect to an ApsaraDB for Redis instance, you must obtain the connection information described in the following table and specify the information in the code.

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 with 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 <user>:<password> format. 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.

Common types of clients

For information about all types of clients supported by Redis, see Clients.

Jedis client

Note We recommend that you select the TairJedis client if you use a performance-enhanced instance of the ApsaraDB for Redis Enhanced Edition (Tair). For more information about performance-enhanced instances, see Performance-enhanced instances.
  1. Download and install the Jedis client. For more information, visit Getting started.
  2. Select a connection method based on your business requirements.
    1. Start the Eclipse client, create a project, and then add the following dependency to the pom file:
      <dependency>
         <groupId>redis.clients</groupId>
         <artifactId>jedis</artifactId>
         <version>Latest non-RC version</version>
         <type>jar</type>
         <scope>compile</scope>
      </dependency>
      Note For information about the latest version of the Jedis client, go to the Releases page.
    2. Enter the following code in the project based on the Jedis client version and modify the code based on the comments.
      Note For information about how to obtain the endpoint of the ApsaraDB for Redis instance and the password of the instance account, see Obtain connection information.
      JedisPoolConfig config = new JedisPoolConfig();
      // Specify the maximum number of idle connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance.
      config.setMaxIdle(200);
      // Specify the maximum number of connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance. 
      config.setMaxTotal(300);
      config.setTestOnBorrow(false);
      config.setTestOnReturn(false);
      // Replace the values of the host and password parameters with the endpoint of the ApsaraDB for Redis instance and the password of the instance account. 
      String host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
      String password = "testaccount:Rp829dlwa";
      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");
          System.out.println(jedis.get("foo"));
          jedis.zadd("sose", 0, "car");
          jedis.zadd("sose", 0, "bike");
          System.out.println(jedis.zrange("sose", 0, -1));
      }
      finally
      {
          if(jedis != null)
          {
              jedis.close();
          }
      }
      /// ... when closing your application:
      pool.destroy();
      JedisPoolConfig config = new JedisPoolConfig();
      // Specify the maximum number of idle connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance.
      config.setMaxIdle(200);
      // Specify the maximum number of connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance.
      config.setMaxTotal(300);
      config.setTestOnBorrow(false);
      config.setTestOnReturn(false);
      // Replace the values of the host and password parameters with the endpoint of the ApsaraDB for Redis instance and the password of the instance account.
      String host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
      String password = "testaccount:Rp829dlwa";
      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);
          }
      }
      import redis.clients.jedis.Jedis;
      public class jedistest {
      public static void main(String[] args) {
      try {
           String host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";// Specify the endpoint of the ApsaraDB for Redis instance.
           int port = 6379;
           Jedis jedis = new Jedis(host, port);
           //Specify the authentication information.
           jedis.auth("password");//password
           String key = "redis";
           String value = "aliyun-redis";
           //Select a database. Default value: 0.
           jedis.select(1);
           //Specify 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. Eclipse may return the following result. The result indicates that the client is connected to the ApsaraDB for Redis instance.
    bar
    [bike, car]
Warning If specific invalid parameters are set or some features are not properly used, errors may occur. For more information about how to troubleshoot errors, see Common Jedis exceptions in ApsaraDB for Redis.

TairJedis client

TairJedis is an ApsaraDB for Redis client that is developed by Alibaba Cloud based on the Jedis client. TairJedis supports the features of Jedis and ApsaraDB for Redis Enhanced Edition (Tair). For example, TairJedis supports the Tair commands of Tair data structures. For more information, see Extended data structures of ApsaraDB for Redis Enhanced Edition (Tair) and Commands supported by extended data structures of ApsaraDB for Redis Enhanced Edition (Tair).

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

For more information, visit alibabacloud-tairjedis-sdk.

PhpRedis client

  1. Download and install the PhpRedis client. For more information, visit phpredis.
  2. Enter the following code in a PHP editor and modify the code based on the comments:
    <?php
     /* Replace the values of the host and port parameters with the endpoint and port number of the ApsaraDB for Redis instance.  */
     $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
     $port = 6379;
     /* Replace the values of the user and pwd parameters with the username and password of the instance account. */
     $user = "testaccount";
     $pwd = "Rp829dlwa";
     $redis = new Redis();
     if ($redis->connect($host, $port) == false) {
             die($redis->getLastError());
       }
     if ($redis->auth($pwd) == false) {
             die($redis->getLastError());
      }
      /* You can perform operations on the instance after the connection is established. For example, you can run the following code to call the set and get methods.  */
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     $value = $redis->get("foo");
     echo $value;
     ?>
    <?php
     /* Replace the values of the host and port parameters with the endpoint and port number of the ApsaraDB for Redis instance.  */
     $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
     $port = 6379;
     /* Replace the values of the user and pwd parameters with the username and password of the instance account. */
     $user = "test_username";
     $pwd = "password";
     $redis = new Redis();
     if ($redis->connect($host, $port) == false) {
             die($redis->getLastError());
       }
     if ($redis->auth($pwd) == false) {
             die($redis->getLastError());
      }
      /* You can perform operations on the instance after the connection is established. For example, you can run the following code to use the TairString data structure.  */
     if ($redis->set("foo", "bar") == false) {
             die($redis->getLastError());
     }
     /* Returns: 1 */
     $redis->rawCommand("CAS", "foo", "bar", "bzz");
     /* Returns: 1 */
     $redis->rawCommand("CAD", "foo", "bzz");
     /* Returns: OK */
     $redis->rawCommand("EXSET", "foo", "200", "VER", "1");
     /* ERR update version is stale */
     $redis->rawCommand("EXSET", "foo", "300", "VER", "10");
     /* Returns : ["OK", " ", VERSION] */
     $redis->rawCommand("EXCAS", "foo", "300", "1");
     ?>
    Note
  3. Run the preceding code to connect to the ApsaraDB for Redis instance.
    For more information, visit phpredis.
Note For more information about how to troubleshoot the Cannot assign requested address error when this error is returned to the client, see The "Cannot assign requested address" error occurs when short-lived connections are used to access ApsaraDB for Redis.

redis-py client

  1. Download and install the redis-py client. For more information, visit redis-py.
  2. Enter the following code in Python 2 and modify the code based on the comments:
    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    # Replace the values of the host and port parameters with the endpoint and port number of the ApsaraDB for Redis instance. 
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # Replace the value of the pwd parameter with the password of the instance account. 
    pwd = 'testaccount:Rp829dlwa'
    r = redis.StrictRedis(host=host, port=port, password=pwd)
    # You can perform operations on the instance after the connection is established. For example, you can run the following code to call the set and get methods. 
    r.set('foo', 'bar');
    print r.get('foo')
    #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    # Replace the values of the host and port parameters with the endpoint and port number of the ApsaraDB for Redis instance. 
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    # Replace the value of the pwd parameter with the password of the instance account. 
    pwd = 'testaccount:Rp829dlwa'
    r = redis.StrictRedis(host=host, port=port, password=pwd)
    # You can perform operations on the instance after the connection is established. For example, you can run the following code to use the TairString data structure. 
    print(r.execute_command('CAS foo bar bzz'))
    print(r.execute_command('CAD foo bzz'))
    print(r.execute_command('EXSET foo 200 VER 1'))
    try:
        r.execute_command('EXSET foo 300 VER 10')
    except:
        print("The attached version is different from the server version, the operation will fail. ")
    print(r.execute_command('EXCAS foo 300 1'))
    Note
  3. Run the preceding code to connect to the ApsaraDB for Redis instance.

Spring Data Redis client

  1. Download and install the Spring Data Redis client
  2. Enter the following code in a Spring Data Redis editor and modify the code based on the comments:
    @Bean
         JedisConnectionFactory redisConnectionFactory() {
             RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", port);
     
             JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
             // Specify the maximum number of connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance. 
             jedisPoolConfig.setMaxTotal(30);
             //Specify the maximum number of idle connections based on your business needs. The value cannot exceed the maximum number of connections supported by the ApsaraDB for Redis instance. 
             jedisPoolConfig.setMaxIdle(20);
             // Close testOn[Borrow|Return] to prevent additional PING commands from being generated. 
             jedisPoolConfig.setTestOnBorrow(false);
             jedisPoolConfig.setTestOnReturn(false);
     
             JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling().poolConfig(
                 jedisPoolConfig).build();
     
             return new JedisConnectionFactory(config, jedisClientConfiguration);
         }
        @Bean
        LettuceConnectionFactory redisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration("host", 6379);
            return new LettuceConnectionFactory(config);
        }
    Note
    • For information about how to obtain the endpoint of the ApsaraDB for Redis instance and the password of the instance account, see Obtain connection information.
    • By default, Spring Data Redis 2.0 and later use Lettuce as the driver. If you want to switch over to Jedis, you must exclude the Lettuce dependency and add the Jedis dependency. Example:
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
          <exclusions>
              <exclusion>
                  <artifactId>lettuce-core</artifactId>
                  <groupId>io.lettuce</groupId>
              </exclusion>
          </exclusions>
      </dependency>
      
      <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
          <version>Latest non-RC version</version>
      </dependency>
  3. Run the preceding code to connect to the ApsaraDB for Redis instance.
    For more information, visit Spring Data Redis.

C or C++ client

  1. Run the following commands 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 based on the comments:
    #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 r-bp10noxlhcoim2****.redis.rds.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;
    }
    #include <iostream>
    #include <string>
    #include <string.h>
    #include <hiredis/hiredis.h>
    using namespace std;
     
    int main(int argc, char **argv) {
        unsigned int j;
        redisContext *c;
        redisReply *reply;
        if (argc < 3) {
                printf("Usage: example r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 password\n");
                exit(0);
        }
        const char *hostname = argv[1];
        const int port = atoi(argv[2]);
        const char *password = argv[3];
        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 = (redisReply *)redisCommand(c, "AUTH %s", password);
        printf("AUTH: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* PING server */
        reply = (redisReply *)redisCommand(c,"PING");
        printf("PING: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* The following code provides an example on how to use the TairString data structure. */
        reply = (redisReply *)redisCommand(c,"SET foo bar");
        printf("SET: %s\n", reply->str);
        freeReplyObject(reply);
    
        reply = (redisReply *)redisCommand(c,"CAS foo bar bzz");
        printf("CAS: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        reply = (redisReply *)redisCommand(c,"CAD foo bzz");
        printf("CAD: %lld\n", reply->integer);
        freeReplyObject(reply);
    
        /* TairString exstrtype */
        reply = (redisReply *)redisCommand(c,"EXSET foo 200 VER 1");
        printf("EXSET: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* The attached version is different from the server version, the operation will fail */
        reply = (redisReply *)redisCommand(c,"EXSET foo 300 VER 10");
        printf("EXSET: %s\n", reply->str);
        freeReplyObject(reply);
    
        /* Compare the specified version to update the value, and the update is successful
        when the version in the engine is the same as the specified one */
        reply = (redisReply *)redisCommand(c,"EXCAS foo 300 1");
        if (reply->type == REDIS_REPLY_ARRAY) {
            /* ["OK", "", version], The middle value is an empty string, meaningless when successful */
            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;
    }
    Note
  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 r-bp10noxlhcoim2****.redis.rds.aliyuncs.com 6379 instance_id password

.NET client

Warning If you need to switch over to 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 to disable the support for the cluster syntax of open source Redis, and restart the client. Otherwise, the following error message is returned: Multiple databases are not supported on this server; cannot switch to database. For more information, see Modify parameters of an instance.
  1. Download and install the StackExchange.Redis client.
  2. Enter the following code in the client and modify the code based on the comments:
    using StackExchange.Redis;
     // Specify the endpoint, port number, and password of the ApsaraDB for Redis instance. 
     private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa,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;
     }
    using System;
    using StackExchange.Redis;
    
    namespace CSharpTestRedis
    {
        class Program
        {  
            // Specify the endpoint, port number, and password of the ApsaraDB for Redis instance. 
    		private static ConfigurationOptions connDCS = ConfigurationOptions.Parse("r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379,password=testaccount:Rp829dlwa");
            //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(connDCS);
                        }
                    }
                }
                return redisConn;
            }
            static void Main(string[] args)
            {
                redisConn = getRedisConn();
                var db = redisConn.GetDatabase();
    
                var ret = db.Execute("set", "foo", "bal");
                Console.WriteLine("set " + ret);
                ret = db.Execute("CAS", "foo", "bal", "bzz");
                Console.WriteLine("CAS " + ret);
                ret = db.Execute("CAD", "foo", "bzz");
                Console.WriteLine("CAD " + ret);
                ret = db.Execute("EXSET", "foo", "200", "VER", "1");
                Console.WriteLine("EXSET " + ret);
                
                try {
                    ret = db.Execute("EXSET", "foo", "300", "VER", "10");
                    Console.WriteLine("EXSET " + ret);
                } catch (Exception ex) {
                    Console.WriteLine("ERR : " + ex.ToString());
                }
                // ["OK", "", version], The middle value is an empty string, meaningless when successful.
                db.Execute("EXCAS", "foo", "300", "1");
                Console.WriteLine("END");
            }
        }
    }
    Note
    • For information about how to obtain the endpoint of the ApsaraDB for Redis instance and the password of the instance account, see Obtain connection information.
    • If you use a performance-enhanced instance of the ApsaraDB for Redis Enhanced Edition (Tair), you can click the preceding Code for ApsaraDB for Redis Enhanced Edition (Tair) instances tab to view the example on how to use the TairString data structure. For more information about performance-enhanced instances, see Performance-enhanced instances. For more information about the data structures, see Commands supported by extended data structures of ApsaraDB for Redis Enhanced Edition (Tair).
    • ConfigurationOptions is a core object of the StackExchange.Redis client. ConfigurationOptions is shared and reused by the client. The singleton pattern is recommended. For more information about parameter settings, see Configuration Options.
    • GetDatabase() returns a lightweight object. You can obtain this object from the ConnectionMultiplexer object.
       redisConn = getRedisConn();
       var db = redisConn.GetDatabase();
  3. Use one of the following common data structures to perform operations. These data structures are slightly different from those of native Redis APIs.
    //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]);
    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 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 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 );
    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();

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 based on the comments:
    var redis = require("redis"),
    // Specify the port number and endpoint of the ApsaraDB for Redis instance. 
    client = redis.createClient(6379, "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com", {detect_buffers: true});
    // Specify the password of the instance account. 
    client.auth("testaccount:Rp829dlwa", redis.print)
    // Write data to the instance. 
    client.set("key", "OK");
    // Query data from the ApsaraDB for Redis instance. The returned data is of the STRING type. 
    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();
    var redis = require("redis");
    // Replace the values of the host and port parameters with the endpoint and port number of the ApsaraDB for Redis instance. 
    var client = redis.createClient({host : 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com', port : 6379});
    // Specify the password of the instance account. 
    client.auth("testaccount:Rp829dlwa", redis.print)
    
    client.set("foo", "bar");
    client.get("foo", function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log(reply.toString()); // print `OK`
        }
    });
    // If the input parameter is a buffer, the returned value is also a buffer. 
    client.get(new Buffer("foo"), function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log(reply.toString()); // print `<Buffer 4f 4b>`
        }
    });
    
    // The following code provides an example on how to use the TairString data structure. 
    client.sendCommand('CAS', ['foo', 'bar', 'bzz'], function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log('CAS : %s', reply.toString());
        }
    });
    
    client.sendCommand('CAD', ['foo', 'bzz'], function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log('CAD : %s', reply.toString());
        }
    });
    
    client.sendCommand('EXSET', ['foo', '200', 'VER', '1'], function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log('EXSET : %s', reply.toString());
        }
    });
    
    client.sendCommand('EXSET', ['foo', '300', 'VER', '10'], function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log('EXSET : %s', reply.toString());
        }
    });
    
    client.sendCommand('EXCAS', ['foo', '300', '1'], function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log('EXCAS : %s', reply.toString()); // print `<Buffer 4f 4b>`
        }
    });
    
    client.quit();
    Note
  3. Run the preceding code to connect to the ApsaraDB for Redis instance.

go-redis client

package main

import (
	"github.com/go-redis/redis"
	"fmt"
)

func ExampleClient() {
	client := redis.NewClient(&redis.Options{
        // Specify the endpoint and port number of the ApsaraDB for Redis instance.
		Addr:     "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
        // Specify the password of the instance account.
		Password: "testaccount:Rp829dlwa",
		DB:       0,  // use default DB
	})
    // The following code provides an example on how to call the set and get methods. 
	err := client.Set("foo", "bar", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := client.Get("foo").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("set : foo -> ", val)
}

func main() {
	ExampleClient()
}
package main

import (
	"github.com/go-redis/redis"
	"fmt"
)

func ExampleClient() {
	client := redis.NewClient(&redis.Options{
        // Specify the endpoint and port number of the ApsaraDB for Redis instance.
		Addr:     "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
        // Specify the password of the instance account.
		Password: "testaccount:Rp829dlwa", // no password set
		DB:       0,  // use default DB
	})

	err := client.Set("foo", "bar", 0).Err()
	if err != nil {
		panic(err)
	}

	val, err := client.Get("foo").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println("set : foo -&gt; ", val)
	
	// The following code provides an example on how to use the TairString data structure.
	res, err := client.Do("CAS", "foo", "bar", "bzz").Result()
	fmt.Println("CAS : ", res)

	res, err = client.Do("CAD", "foo", "bzz").Result()
	fmt.Println("CAD : ", res)

	res, err = client.Do("EXSET", "foo", "200", "VER", "1").Result()
	fmt.Println("EXSET : ", res)

	res, err = client.Do("EXSET", "foo", "300", "VER", "10").Result()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("EXSET : ", res)

	res, err = client.Do("EXCAS", "foo", "300", "1").Result()
	fmt.Println("EXCAS : ", res)
}

func main() {
	ExampleClient()
}
Note

Lettuce client

The Lettuce client supports synchronous and asynchronous communication based on comprehensive Redis APIs. The 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 nodes or data nodes, a connection timeout may occur. This may result in the failure to reconnect to ApsaraDB for Redis. To prevent such risks, we recommend that you use a Jedis client to connect to ApsaraDB for Redis instances. For more information, see Jedis client.

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

For more information, visit lettuce-core.