edit-icon download-icon

Connect to database with Redis clients

Last Updated: Feb 13, 2018

As ApsaraDB for Redis is completely compatible with the native database service, their databases are connected in similar ways. Any clients compatible with the Redis protocol can access Alibaba Cloud ApsaraDB for Redis. You can choose any Redis clients based on their application features.

Note: ApsaraDB for Redis only supports access requests from the Alibaba Cloud intranet rather than those from the Internet. That means only Redis clients installed on ECS instances of the same node can be connected to ApsaraDB for Redis for data operations.

To use Redis clients, see Clients.

Jedis client

The Jedis client can access ApsaraDB for Redis through either of the following methods:

  • Jedis single-connection

  • JedisPool connection

Procedure
  1. Click download address to download and install the Jedis client.

  2. Example of Jedis single-connection

    1. Open the Eclipse client, create a project, and enter the following code segment:

      1. import redis.clients.jedis.Jedis;
      2. public class jedistest {
      3. public static void main(String[] args) {
      4. try {
      5. String host = "xx.kvstore.aliyuncs.com";//The access URL is displayed on the console.
      6. int port = 6379;
      7. Jedis jedis = new Jedis(host, port);
      8. //Authentication information
      9. jedis.auth("password");//password
      10. String key = "redis";
      11. String value = "aliyun-redis";
      12. //Select a database. (The default value is 0.)
      13. jedis.select(1);
      14. //Set a key.
      15. jedis.set(key, value);
      16. System.out.println("Set Key " + key + " Value: " + value);
      17. //Get the key.
      18. String getvalue = jedis.get(key);
      19. System.out.println("Get Key " + key + " ReturnValue: " + getvalue);
      20. jedis.quit();
      21. jedis.close();
      22. } catch (Exception e) {
      23. e.printStackTrace();
      24. }
      25. }
      26. }
    2. Run the project. If the following result is output on the Eclipse console, you have successfully connected to ApsaraDB for Redis.

      1. Set Key redis Value aliyun-redis
      2. Get Key redis ReturnValue aliyun-redis

      Then you can use your local Jedis client to operate your ApsaraDB for Redis instance. You can also connect to your ApsaraDB for Redis instance through JedisPool.

  3. Example of JedisPool connection

    1. Open the Eclipse client, create a project, and configure the pom file as follows:

      1. <dependency>
      2. <groupId>redis.clients</groupId>
      3. <artifactId>jedis</artifactId>
      4. <version>2.7.2</version>
      5. <type>jar</type>
      6. <scope>compile</scope>
      7. </dependency>
    2. Add the following application to the project:

      1. import org.apache.commons.pool2.PooledObject;
      2. import org.apache.commons.pool2.PooledObjectFactory;
      3. import org.apache.commons.pool2.impl.DefaultPooledObject;
      4. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
      5. import redis.clients.jedis.HostAndPort;
      6. import redis.clients.jedis.Jedis;
      7. import redis.clients.jedis.JedisPool;
      8. import redis.clients.jedis.JedisPoolConfig;
    3. If your Jedis client version is Jedis-2.7.2, enter the following code in the project:

      1. JedisPoolConfig config = new JedisPoolConfig();
      2. //Maximum idle connections, which are evaluated by the application. Do not set it to a value greater than the maximum connections of an ApsaraDB for Redis instance.
      3. config.setMaxIdle(200);
      4. //Maximum connections, which are evaluated by the application. Do not set it to a value greater than the maximum connections of an ApsaraDB for Redis instance.
      5. config.setMaxTotal(300);
      6. config.setTestOnBorrow(false);
      7. config.setTestOnReturn(false);
      8. String host = "*.aliyuncs.com";
      9. String password = "password";
      10. JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
      11. Jedis jedis = null;
      12. try {
      13. jedis = pool.getResource();
      14. /// ... do stuff here ... for example
      15. jedis.set("foo", "bar");
      16. String foobar = jedis.get("foo");
      17. jedis.zadd("sose", 0, "car");
      18. jedis.zadd("sose", 0, "bike");
      19. Set<String> sose = jedis.zrange("sose", 0, -1);
      20. } finally {
      21. if (jedis != null) {
      22. jedis.close();
      23. }
      24. }
      25. /// ... when closing your application:
      26. pool.destroy();
    4. If your Jedis client version is Jedis-2.6 or Jedis-2.5, enter the following code in the project:

      1. JedisPoolConfig config = new JedisPoolConfig();
      2. //Maximum idle connections, which are evaluated by the application. Do not set it to a value greater than the maximum connections of an ApsaraDB for Redis instance.
      3. config.setMaxIdle(200);
      4. //Maximum connections, which are evaluated by the application. Do not set it to a value greater than the maximum connections of an ApsaraDB for Redis instance.
      5. config.setMaxTotal(300);
      6. config.setTestOnBorrow(false);
      7. config.setTestOnReturn(false);
      8. String host = "*.aliyuncs.com";
      9. String password = "password";
      10. JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
      11. Jedis jedis = null;
      12. boolean broken = false;
      13. try {
      14. jedis = pool.getResource();
      15. /// ... do stuff here ... for example
      16. jedis.set("foo", "bar");
      17. String foobar = jedis.get("foo");
      18. jedis.zadd("sose", 0, "car");
      19. jedis.zadd("sose", 0, "bike");
      20. Set<String> sose = jedis.zrange("sose", 0, -1);
      21. } catch(Exception e) {
      22. broken = true;
      23. } finally {
      24. if (broken) {
      25. pool.returnBrokenResource(jedis);
      26. } else if (jedis != null) {
      27. pool.returnResource(jedis);
      28. }
      29. }
    5. Run the project. If the following result is output on the Eclipse console, you have successfully connected to ApsaraDB for Redis.

      1. Set Key redis Value aliyun-redis
      2. Get Key redis ReturnValue aliyun-redis

      Then you can use your local Jedis client to operate your ApsaraDB for Redis instance.

phpredis client

Procedure
  1. Click download address to download and install the phpredis client.

  2. In any editor supporting php editing, enter the following code:

    1. <?php
    2. /* Replace the following parameter values with the host of the connected instance and the port number. */
    3. $host = "localhost";
    4. $port = 6379;
    5. /* Replace the following parameter values with the instance ID and instance password. */
    6. $user = "test_username";
    7. $pwd = "test_password";
    8. $redis = new Redis();
    9. if ($redis->connect($host, $port) == false) {
    10. die($redis->getLastError());
    11. }
    12. if ($redis->auth($pwd) == false) {
    13. die($redis->getLastError());
    14. }
    15. /* The database can be operated after authentication. For more information, see https://github.com/phpredis/phpredis. */
    16. if ($redis->set("foo", "bar") == false) {
    17. die($redis->getLastError());
    18. }
    19. $value = $redis->get("foo");
    20. echo $value;
    21. ?>
  3. Run the preceding code. Then You can use your local phpredis client to access your ApsaraDB for Redis instance. For more information, see https://github.com/phpredis/phpredis.

redis-py client

Procedure
  1. Click download address to download and install the redis-py client.

  2. In any editor supporting Python editing, enter the following code. Then you can use a local redis-py client to connect to and operate the database.

  1. #!/usr/bin/env python
  2. #-*- coding: utf-8 -*-
  3. import redis
  4. #Replace the following parameter values with the host of the connected instance and the port number.
  5. host = 'localhost'
  6. port = 6379
  7. #Replace the following parameter values with the instance password.
  8. pwd = 'test_password'
  9. r = redis.StrictRedis(host=host, port=port, password=pwd)
  10. #The database can be operated after a connection is created. For more information, see https://github.com/andymccurdy/redis-py.
  11. r.set('foo', 'bar');
  12. print r.get('foo')

C/C++ client

Procedure
  1. Download, compile, and install the C client. The code for compiling and installation is as follows:

    1. git clone https://github.com/redis/hiredis.git
    2. cd hiredis
    3. make
    4. sudo make install
  2. Enter the following code in the C/C++ editor:

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. #include <string.h>
    4. #include <hiredis.h>
    5. int main(int argc, char **argv) {
    6. unsigned int j;
    7. redisContext *c;
    8. redisReply *reply;
    9. if (argc < 4) {
    10. printf("Usage: example xxx.kvstore.aliyuncs.com 6379 instance_id password\n");
    11. exit(0);
    12. }
    13. const char *hostname = argv[1];
    14. const int port = atoi(argv[2]);
    15. const char *instance_id = argv[3];
    16. const char *password = argv[4];
    17. struct timeval timeout = { 1, 500000 }; // 1.5 seconds
    18. c = redisConnectWithTimeout(hostname, port, timeout);
    19. if (c == NULL || c->err) {
    20. if (c) {
    21. printf("Connection error: %s\n", c->errstr);
    22. redisFree(c);
    23. } else {
    24. printf("Connection error: can't allocate redis context\n");
    25. }
    26. exit(1);
    27. }
    28. /* AUTH */
    29. reply = redisCommand(c, "AUTH %s", password);
    30. printf("AUTH: %s\n", reply->str);
    31. freeReplyObject(reply);
    32. /* PING server */
    33. reply = redisCommand(c,"PING");
    34. printf("PING: %s\n", reply->str);
    35. freeReplyObject(reply);
    36. /* Set a key */
    37. reply = redisCommand(c,"SET %s %s", "foo", "hello world");
    38. printf("SET: %s\n", reply->str);
    39. freeReplyObject(reply);
    40. /* Set a key using binary safe API */
    41. reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
    42. printf("SET (binary API): %s\n", reply->str);
    43. freeReplyObject(reply);
    44. /* Try a GET and two INCR */
    45. reply = redisCommand(c,"GET foo");
    46. printf("GET foo: %s\n", reply->str);
    47. freeReplyObject(reply);
    48. reply = redisCommand(c,"INCR counter");
    49. printf("INCR counter: %lld\n", reply->integer);
    50. freeReplyObject(reply);
    51. /* again ... */
    52. reply = redisCommand(c,"INCR counter");
    53. printf("INCR counter: %lld\n", reply->integer);
    54. freeReplyObject(reply);
    55. /* Create a list of numbers, from 0 to 9 */
    56. reply = redisCommand(c,"DEL mylist");
    57. freeReplyObject(reply);
    58. for (j = 0; j < 10; j++) {
    59. char buf[64];
    60. snprintf(buf,64,"%d",j);
    61. reply = redisCommand(c,"LPUSH mylist element-%s", buf);
    62. freeReplyObject(reply);
    63. }
    64. /* Let's check what we have inside the list */
    65. reply = redisCommand(c,"LRANGE mylist 0 -1");
    66. if (reply->type == REDIS_REPLY_ARRAY) {
    67. for (j = 0; j < reply->elements; j++) {
    68. printf("%u) %s\n", j, reply->element[j]->str);
    69. }
    70. }
    71. freeReplyObject(reply);
    72. /* Disconnects and frees the context */
    73. redisFree(c);
    74. return 0;
    75. }
  3. Compile the preceding code.

    1. gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
  4. Perform the test run.

    1. example xxx.kvstore.aliyuncs.com 6379 instance_id password

So far, the C/C++ client can connect to ApsaraDB for Redis.

.net client

Procedure
  1. Download and use the .net client.

    1. git clone https://github.com/ServiceStack/ServiceStack.Redis
  2. Create a .net project in 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 created .net project to connect to ApsaraDB for Redis. For more information about port use, see https://github.com/ServiceStack/ServiceStack.Redis.

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. using ServiceStack.Redis;
    7. namespace ServiceStack.Redis.Tests
    8. {
    9. class Program
    10. {
    11. public static void RedisClientTest()
    12. {
    13. string host = "127.0.0.1";/*IP address of the access host*/
    14. string password = "password";/*Password*/
    15. RedisClient redisClient = new RedisClient(host, 6379, password);
    16. string key = "test-aliyun";
    17. string value = "test-aliyun-value";
    18. redisClient.Set(key, value);
    19. string listKey = "test-aliyun-list";
    20. System.Console.WriteLine("set key " + key + " value " + value);
    21. string getValue = System.Text.Encoding.Default.GetString(redisClient.Get(key));
    22. System.Console.WriteLine("get key " + getValue);
    23. System.Console.Read();
    24. }
    25. public static void RedisPoolClientTest()
    26. {
    27. string[] testReadWriteHosts = new[] {
    28. "redis://password@127.0.0.1:6379"/*redis://password@access address:port number*/
    29. };
    30. RedisConfig.VerifyMasterConnections = false;//You must set the parameter.
    31. PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*Number of connection pools*/, 10/*Connection pool timeout time*/, testReadWriteHosts);for (int i = 0; i < 100; i++){
    32. IRedisClient redisClient = redisPoolManager.GetClient();//Obtain the connection.
    33. RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient;
    34. redisNativeClient.Client = null;//ApsaraDB for Redis does not support client setname. Therefore, you must set the client object to null.
    35. try
    36. {
    37. string key = "test-aliyun1111";
    38. string value = "test-aliyun-value1111";
    39. redisClient.Set(key, value);
    40. string listKey = "test-aliyun-list";
    41. redisClient.AddItemToList(listKey, value);
    42. System.Console.WriteLine("set key " + key + " value " + value);
    43. string getValue = redisClient.GetValue(key);
    44. System.Console.WriteLine("get key " + getValue);
    45. redisClient.Dispose();//
    46. }catch (Exception e)
    47. {
    48. System.Console.WriteLine(e.Message);
    49. }
    50. }
    51. System.Console.Read();
    52. }static void Main(string[] args)
    53. {
    54. //Single connection mode
    55. RedisClientTest();
    56. //Connection pool mode
    57. RedisPoolClientTest();
    58. }
    59. }
    60. }

node-redis client

Procedure
  1. Download and install node-redis.

    1. npm install hiredis redis
  2. Enter and run the following code in the node-redis client to connect to ApsaraDB for Redis.

    1. var redis = require("redis"),
    2. client = redis.createClient({detect_buffers: true});
    3. client.auth("password", redis.print)
  3. Use ApsaraDB for Redis.

    1. // Write data.
    2. client.set("key", "OK");
    3. // Obtain data and a string is returned.
    4. client.get("key", function (err, reply) {
    5. console.log(reply.toString()); // print `OK`
    6. });
    7. // If a buffer is transmitted, a buffer is returned.
    8. client.get(new Buffer("key"), function (err, reply) {
    9. console.log(reply.toString()); // print `<Buffer 4f 4b>`
    10. });
    11. client.quit();
Thank you! We've received your feedback.