閱讀527 返回首頁    go 阿裏雲


Redis客戶端連接__連接實例_快速入門_雲數據庫 Redis 版-阿裏雲

Redis 客戶端連接

由於雲數據庫 Redis 提供的數據庫服務與原生的數據庫服務完全兼容,連接數據庫的方式也基本類似。任何兼容 Redis 協議的客戶端都可以訪問阿裏雲 ApsaraDB for Redis 服務,您可以根據自身應用特點選用任何 Redis 客戶端。

注意:雲數據庫 Redis 版僅支持阿裏雲內網訪問,不支持外網訪問,即隻有在同節點的 ECS上安裝 Redis 客戶端才能與雲數據庫建立連接並進行數據操作。

Redis 的客戶端請參考 https://redis.io/clients

Jedis 客戶端

Jedis 下載

點擊 參考地址

Jedis 單連接示例

  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";//控製台顯示訪問地址
  6. int port = 6379;
  7. Jedis jedis = new Jedis(host, port);
  8. //鑒權信息
  9. jedis.auth("password");//password
  10. String key = "redis";
  11. String value = "aliyun-redis";
  12. //select db默認為0
  13. jedis.select(1);
  14. //set一個key
  15. jedis.set(key, value);
  16. System.out.println("Set Key " + key + " Value: " + value);
  17. //get 設置進去的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. }

JedisPool 連接池示例

配置文件

用戶根據自己選擇的客戶端版本配置pom配置文件,配置如下:

  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>
需要添加的引用
  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;
Jedis-2.7.2示例
  1. JedisPoolConfig config = new JedisPoolConfig();
  2. //最大空閑連接數, 應用自己評估,不要超過ApsaraDB for Redis每個實例最大的連接數
  3. config.setMaxIdle(200);
  4. //最大連接數, 應用自己評估,不要超過ApsaraDB for Redis每個實例最大的連接數
  5. config.setMaxTotal(300);
  6. config.setTestOnBorrow(false);
  7. config.setTestOnReturn(false);
  8. String host = "*.aliyuncs.com";
  9. String 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();
jedis-2.6、Jedis-2.5示例
  1. JedisPoolConfig config = new JedisPoolConfig();
  2. //最大空閑連接數, 應用自己評估,不要超過ApsaraDB for Redis每個實例最大的連接數
  3. config.setMaxIdle(200);
  4. //最大連接數, 應用自己評估,不要超過ApsaraDB for Redis每個實例最大的連接數
  5. config.setMaxTotal(300);
  6. config.setTestOnBorrow(false);
  7. config.setTestOnReturn(false);
  8. String host = "*.aliyuncs.com";
  9. String 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. }

phpredis 客戶端

phpredis下載

點擊 參考地址

連接代碼示例

  1. <?php
  2. /* 這裏替換為連接的實例host和port */
  3. $host = "localhost";
  4. $port = 6379;
  5. /* 這裏替換為實例id和實例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. /* user:password 拚接成AUTH的密碼 */
  13. if ($redis->auth($user . ":" . $pwd) == false) {
  14. die($redis->getLastError());
  15. }
  16. /* 認證後就可以進行數據庫操作,詳情文檔參考https://github.com/phpredis/phpredis */
  17. if ($redis->set("foo", "bar") == false) {
  18. die($redis->getLastError());
  19. }
  20. $value = $redis->get("foo");
  21. echo $value;
  22. ?>

redis-py客戶端

redis-py下載

點擊 參考地址

連接代碼示例

  1. #!/usr/bin/env python
  2. #-*- coding: utf-8 -*-
  3. import redis
  4. #這裏替換為連接的實例host和port
  5. host = 'localhost'
  6. port = 6379
  7. #這裏替換為實例id和實例password
  8. user = 'test_username'
  9. pwd = 'test_password'
  10. #連接時通過password參數指定AUTH信息,由user,pwd通過":"拚接而成
  11. r = redis.StrictRedis(host=host, port=port, password=user+':'+pwd)
  12. #連接建立後就可以進行數據庫操作,詳情文檔參考https://github.com/andymccurdy/redis-py
  13. r.set('foo', 'bar');
  14. print r.get('foo')

C/C++客戶端

下麵是一個 C/C++ 程序使用 ApsaraDB for Redis 的步驟及簡單例子。

  1. 下載編譯安裝C客戶端。
    1. git clone https://github.com/redis/hiredis.git
    2. cd hiredis
    3. make
    4. sudo make install
  2. 編寫測試代碼。

    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 passwordn");
    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: %sn", c->errstr);
    22. redisFree(c);
    23. } else {
    24. printf("Connection error: can't allocate redis contextn");
    25. }
    26. exit(1);
    27. }
    28. /* AUTH */
    29. reply = redisCommand(c, "AUTH %s:%s", instance_id, password);
    30. printf("AUTH: %sn", reply->str);
    31. freeReplyObject(reply);
    32. /* PING server */
    33. reply = redisCommand(c,"PING");
    34. printf("PING: %sn", reply->str);
    35. freeReplyObject(reply);
    36. /* Set a key */
    37. reply = redisCommand(c,"SET %s %s", "foo", "hello world");
    38. printf("SET: %sn", 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): %sn", reply->str);
    43. freeReplyObject(reply);
    44. /* Try a GET and two INCR */
    45. reply = redisCommand(c,"GET foo");
    46. printf("GET foo: %sn", reply->str);
    47. freeReplyObject(reply);
    48. reply = redisCommand(c,"INCR counter");
    49. printf("INCR counter: %lldn", reply->integer);
    50. freeReplyObject(reply);
    51. /* again ... */
    52. reply = redisCommand(c,"INCR counter");
    53. printf("INCR counter: %lldn", 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) %sn", j, reply->element[j]->str);
    69. }
    70. }
    71. freeReplyObject(reply);
    72. /* Disconnects and frees the context */
    73. redisFree(c);
    74. return 0;
    75. }
  3. 編譯。

    1. gcc -o example -g example.c -I /usr/local/include/hiredis –lhiredis
  4. 測試運行。

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

.net客戶端

下麵是一個 .net 程序使用 ApsaraDB for Redis 的步驟及簡單例子。

  1. 下載及使用.net客戶端。
    1. git clone https://github.com/ServiceStack/ServiceStack.Redis
  2. 新建 .net 項目。
  3. 添加客戶端引用,引用文件在庫文件的 ServiceStack.Redis/lib/tests 中。

    測試代碼示例:
    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";/*訪問host地址*/
    14. string password = "fb92bf2e0abf11e5:123456128a1A";/*實例id:密碼*/
    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://:fb92bf2e0abf11e5:1234561178a1A@127.0.0.1:6379"/*redis://:實例id:密碼@訪問地址:端口*/
    29. };
    30. RedisConfig.VerifyMasterConnections = false;//需要設置
    31. PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*連接池個數*/, 10/*連接池超時時間*/, testReadWriteHosts);
    32. for (int i = 0; i < 100; i++)
    33. {
    34. IRedisClient redisClient = redisPoolManager.GetClient();//獲取連接
    35. RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient;
    36. redisNativeClient.Client = null;//ApsaraDB for Redis不支持client setname所以這裏需要顯示的把client對象置為null
    37. try
    38. {
    39. string key = "test-aliyun1111";
    40. string value = "test-aliyun-value1111";
    41. redisClient.Set(key, value);
    42. string listKey = "test-aliyun-list";
    43. redisClient.AddItemToList(listKey, value);
    44. System.Console.WriteLine("set key " + key + " value " + value);
    45. string getValue = redisClient.GetValue(key);
    46. System.Console.WriteLine("get key " + getValue);
    47. redisClient.Dispose();//
    48. }
    49. catch (Exception e)
    50. {
    51. System.Console.WriteLine(e.Message);
    52. }
    53. }
    54. System.Console.Read();
    55. }
    56. static void Main(string[] args)
    57. {
    58. //單鏈接模式
    59. RedisClientTest();
    60. //連接池模式
    61. RedisPoolClientTest();
    62. }
    63. }
    64. }

    詳細的接口用法請參見 https://github.com/ServiceStack/ServiceStack.Redis

node-redis 客戶端

  1. 安裝 node-redis。

    1. npm install hiredis redis
  2. 連接 ApsaraDB for Redis。

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

    1. // 寫入數據
    2. client.set("key", "OK");
    3. // 獲取數據,返回String
    4. client.get("key", function (err, reply) {
    5. console.log(reply.toString()); // print `OK`
    6. });
    7. // 如果傳入一個Buffer,返回也是一個Buffer
    8. client.get(new Buffer("key"), function (err, reply) {
    9. console.log(reply.toString()); // print `<Buffer 4f 4b>`
    10. });
    11. client.quit();

最後更新:2016-12-16 17:39:23

  上一篇:go DMS 登錄雲數據庫__連接實例_快速入門_雲數據庫 Redis 版-阿裏雲
  下一篇:go Redis-cli連接__連接實例_快速入門_雲數據庫 Redis 版-阿裏雲