さまざまなプログラミング言語のクライアントを使用して、ApsaraDB for Redis インスタンスに接続できます。

ApsaraDB for Redis のデータベースサービスは、Redis データベースサービスと完全に互換性があります。 したがって、同様の方法で両方のデータベースサービスに接続することができます。 Redis プロトコルと互換性のあるすべてのクライアントは、ApsaraDB for Redis への接続をサポートしています。 いずれのクライアントも、アプリケーションの機能に応じて使用することができます。

重要

Redis クライアントの詳細については、「http://redis.io/clients」をご参照ください。

Jedis クライアント

以下のいずれかの方法で、Jedis クライアントを使用して ApsaraDB for Redis に接続します。

  • 単一 Jedis 接続
  • JedisPool ベースの接続

Jedis クライアントを使用して ApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. Jedis クライアントをダウンロードしてインストールします。 詳細は、「Jedis」をご参照ください。

  2. 単一 Jedis 接続の例

    1. Eclipse クライアントを開き、プロジェクトを作成してから、以下のコードを入力します。

      import redis.clients.jedis.Jedis;
      public class jedistest {
      public static void main(String[] args) {
      try {
           String host = "xx.kvstore.aliyuncs.com";//You can view the endpoint 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 value.
           String getvalue = jedis.get(key);
           System.out.println("Get Key " + key + " ReturnValue: " + getvalue);
           jedis.quit();
           jedis.close();
      } 
      catch (Exception e) {
       e.printStackTrace();
       }
      }
      }
    2. プロジェクトを実行します。 Eclipse コンソールで以下の結果が表示された場合、ApsaraDB for Redis に接続されています。

      Set Key redis Value aliyun-redis
      Get Key redis ReturnValue aliyun-redis

      接続後は、ローカルの Jedis クライアントを使用して、ApsaraDB for Redis インスタンスを管理することができます。 JedisPool を使用して、ApsaraDB for Redis インスタンスに接続することもできます。

  3. JedisPool ベースの接続の例

    1. Eclipse クライアントを開き、プロジェクトを作成してから、pom ファイルを以下のように設定します。

      <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.2</version>
      <type>jar</type>
      <scope>compile</scope>
      </dependency>
    2. 以下のアプリケーションをプロジェクトに追加します。

      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. お使いの Jedis クライアントのバージョンが 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();
    4. お使いの Jedis クライアントのバージョンが Jedis-2.6 または 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);
       }
      }
    5. プロジェクトを実行します。 Eclipse コンソールに以下の結果が表示された場合、ApsaraDB for Redis に接続されています。

      Set Key redis Value aliyun-redis
      Get Key redis ReturnValue aliyun-redis

      ローカルの Jedis クライアントを使用して、ApsaraDB for Redis インスタンスを管理することができます。

phpredis クライアント

phpredis クライアントを使用してApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. phpredis クライアントをダウンロードしてインストールします。 詳細については、「phpredis」をご参照ください。

  2. PHP の編集をサポートするエディターで、以下のコードを入力します。

    <? php
     /* Replace the following parameter values with the host name and port number of the target instance. */
     $host = "localhost";
     $port = 6379;
     /* Replace the following parameter values with the ID and password of the target 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. コードを実行します。 ローカルの phpredis クライアントを使用して、ApsaraDB for Redis インスタンスに接続することができます。 詳細については、「https://github.com/phpredis/phpredis」をご参照ください。

redis-py クライアント

Redis-py クライアントを使用して ApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. redis-py クライアントをダウンロードしてインストールします。 詳細については、「redis-py」をご参照ください。

  2. Python の編集をサポートするエディターで、以下のコードを入力します。 ローカルの redis-py クライアントを使用して、ApsaraDB for Redis インスタンスに接続し、データベース操作を実行できます。

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import redis
#Replace the following parameter values with the host name and port number of the target instance.
host = 'localhost'
port = 6379
#Replace the following parameter value with the password of the target 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')

C または C++ クライアント

C または C++ クライアントを使用して ApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. 以下のコードを使用して、C クライアントをダウンロード、コンパイル、およびインストールします。

         git clone https://github.com/redis/hiredis.git
         cd hiredis
         make 
         sudo make install
  2. C または C++ エディターで以下のコードを入力します。

         #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. コードをコンパイルします。

    gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. コードをテストします。

     example xxx.kvstore.aliyuncs.com 6379 instance_id password

これで、C またはC++ クライアントが ApsaraDB for Redis インスタンスに接続されました。

.NET client

.NET クライアントを使用して ApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. .NET クライアントをダウンロードして使用します。

     git clone https://github.com/ServiceStack/ServiceStack.Redis
  2. .NET クライアントで .NET プロジェクトを作成します。

  3. ライブラリファイルディレクトリ ServiceStack.Redis/lib/tests に保存されている参照ファイルをクライアントに追加します。

  4. .NET プロジェクトに以下のコードを入力して、ApsaraDB for Redis インスタンスに接続します。 API の詳細については、「https://github.com/ServiceStack/ServiceStack.Redis」をご参照ください。

    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";/*IP address of the host that you want to connect to*/
             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 that you want to connect to:Port*/
     };
     RedisConfig.VerifyMasterConnections = false;//You must set the parameter.
     PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*Number of connections in the pool*/, 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 クライアント

node-redis クライアントを使用して ApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. node-redis クライアントをダウンロードしてインストールします。

    npm install hiredis redis
  2. node-redis クライアントで以下のコードを入力して実行し、ApsaraDB for Redis インスタンスに接続します。

     var redis = require("redis"),
     client = redis.createClient(<port>, <"host">, {detect_buffers: true});
     client.auth("password", redis.print)
    このコードでは、port には ApsaraDB for Redis インスタンスのポートを指定します。 デフォルト値は 6379 です。 host には、ApsaraDB for Redis インスタンスのエンドポイントを指定します。 以下に、port および host の設定例を示します。
    client = redis.createClient(6379, "r-abcdefg.redis.rds.aliyuncs.com", {detect_buffers: true});
  3. ApsaraDB for Redis インスタンスを使用します。

       // Write data to the instance.
     client.set("key", "OK");
     // Query data on the instance. The instance returns data of String type.
     client.get("key", function (err, reply) {
     console.log(reply.toString()); // print `OK`
     });
     // If you specify a buffer, the instance returns a buffer.
     client.get(new Buffer("key"), function (err, reply) {
     console.log(reply.toString()); // print `<Buffer 4f 4b>`
     });
     client.quit();

C# クライアント StackExchange.Redis

C# クライアント StackExchange.Redis を使用してApsaraDB for Redis インスタンスに接続するには、以下の手順に従います。

  1. StackExchange. Redis をダウンロードしてインストールします。

  2. 参照を追加します。
    using StackExchange.Redis;
  3. ConnectionMultiplexer を初期化します。

    ConnectionMultiplexer は StackExchange.Redis のコアであり、アプリケーション全体で共有されます。 ConnectionMultiplexer をシングルトンとして使用する必要があります。 ConnectionMultiplexer は、以下の方法で初期化されます。

     // 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;
     }
    ConfigurationOptions には、keepAlive、connectRetry、name などの複数のオプションが含まれています。 詳細については、「StackExchange.Redis.ConfigurationOptions」をご参照ください。
  4. GetDatabase () は軽量オブジェクトを返します。 このオブジェクトは、ConnectionMultiplexer のオブジェクトから取得できます。

     redisConn = getRedisConn();
     var db = redisConn.GetDatabase();
  5. 以下の例に、5 種類のデータ構造を示します。 これらの例で使用されている API は、 本来の Redis サービスでの使用方法とは異なります。 これらのデータ構造には、文字列、ハッシュ、リスト、セット、およびソートセットが含まれています。

    • 文字列

      //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 );
    • sortedset

      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();