阅读527 返回首页    go 小米 go MIUI米柚


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 版-阿里云