• 将AWS ElastiCache for Redis数据库迁移到阿里云
  • 将SSDB数据库迁移到云数据库Redis版
  • 将Google Cloud Platform Memorystore数据库迁移到阿里云Redis
  • 校验迁移后的数据
  • 申请赔付和复议
  • 根据标签筛选实例
  • 云数据库Redis版是否支持分布式集群的形态?
  • 从节点(Slave)是否会与其主节点(Master)一起保持最新状态?
  • ApsaraDB for Redis默认的数据逐出策略是什么?
  • 云数据库Redis版兼容Redis哪个版本?
  • ApsaraDB for Redis可以配置一个主节点,多个从节点么?
  • ApsaraDB for Redis支持数据持久化吗?
  • ApsaraDB for Redis与Redis是什么关系?
  • ApsaraDB for Redis是否有主从(Master-Slave)双节点备份?
  • ApsaraDB for Redis过期key数据删除规则
  • ApsaraDB for Redis目前是否开放了作为只读节点的从节点(Slave)?
  • 对于每个ApsaraDB for Redis实例(包括集群实例),是否都是有主从两个实例在运行?
  • Redis实例每个DB空间大小和选择DB
  • Redis-benchmark使用介绍
  • 每个实例可以使用多少个DB?
  • Redis-cli连接ApsaraDB for Redis的方法
  • 哪里可以下载ApsaraDB for Redis的客户端?
  • 导入Redis数据示例
  • 使用ApsaraDB for Redis,需要在ECS上安装Redis吗?
  • ApsaraDB for Redis支持通用的redis客户端吗?(如Jedis)
  • ApsaraDB for Redis如何进行性能测试?
  • ApsaraDB for Redis支持哪些Redis功能命令?
  • 连接ApsaraDB for Redis必须要密码吗?在哪里获取密码?
  • 云数据库Redis版支持公网访问吗?
  • 在哪里获取ApsaraDB for Redis的连接地址和实例 ID?
  • 云数据库Redis缓存PHP session变量
  • 使用memtier-benchmark测试Redis集群版性能
  • 使用redis-cli查找大Key
  • 使用redis-cli批量执行命令
  • 以指定频率持续运行相同命令
  • 导出命令执行结果到CSV文件
  • 在Linux命令行实时监控实例状态
  • ApsaraDB for Redis的单个实例是否有CPU处理能力、带宽和连接数等限制?
  • ApsaraDB for Redis是否支持修改配置参数?
  • ApsaraDB for Redis兼容哪些Redis命令和操作?
  • 控制台功能
  • 如何修改ApsaraDB for Redis默认的数据逐出策略?
  • ApsaraDB for Redis缓存的设置方法
  • ApsaraDB for Redis的数据被用户删除了之后,是否还能找回?
  • 包年包月实例是否可以更改规格(扩容/缩容)?
  • 云数据库Redis修改密码的方法
  • 删除Redis中所有数据库的key
  • 为什么我新创建的云数据库Redis版实例的使用量不为0?
  • 如何对ApsaraDB for Redis进行监控?容量满了会自动告警吗?
  • 用客户端连接ApsaraDB for Redis的时候显示密码不对
  • 应用程序访问ApsaraDB for Redis超时后的重连机制
  • 通过公网连接云数据库 Redis-ECS Windows 篇
  • 通过公网连接云数据库Redis-ECS Linux篇
  • on required”...
  • 解决因域名解析失败导致的连接问题
  • 使用ping命令检测ECS与Redis之间的连接
  • 使用telnet命令检测Redis端口连通性
  • 云数据库Redis版支持公网访问吗?
  • Redis集群版实例常见错误返回信息
  • 服务等级协议
  • 云数据库Redis与原生Redis完全兼容,连接数据库的方式也基本相同,您可以根据自身应用特点选用任何兼容Redis协议的客户端程序。本文列举一些常见的客户端程序的代码示例,帮助您快速连接。

    根据客户端程序的部署位置,完成下述操作: 实例的账号(部分客户端程序无需设置) Redis实例默认会创建一个以实例ID命名的账号(例如r-bp10noxlhcoim2****),您也可以创建一个新的账号并赋予权限。更多信息,请参见 创建与管理账号 。 账号的密码

    根据选取账号的不同,密码的填写格式有一定区别:

  • 默认账号 :直接填写密码即可。
  • 打开Eclipse客户端,创建一个Project并配置pom文件,具体内容如下:
    <dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>Latest non-RC version</version>
       <type>jar</type>
       <scope>compile</scope>
    </dependency>
    JedisPoolConfig config = new JedisPoolConfig();
    // 最大空闲连接数,需自行评估,不超过Redis实例的最大连接数
    config.setMaxIdle(200);
    // 最大连接数,需自行评估,不超过Redis实例的最大连接数。
    config.setMaxTotal(300);
    config.setTestOnBorrow(false);
    config.setTestOnReturn(false);
    // 分别将host和password的值替换为实例的连接地址、密码。
    String host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
    String password = "testaccount:Rp829dlwa";
    JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
    Jedis jedis = null;
        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();
    JedisPoolConfig config = new JedisPoolConfig();
    // 最大空闲连接数,需自行评估,不超过Redis实例的最大连接数
    config.setMaxIdle(200);
    // 最大连接数,需自行评估,不超过Redis实例的最大连接数
    config.setMaxTotal(300);
    config.setTestOnBorrow(false);
    config.setTestOnReturn(false);
    // 分别将host和password的值替换为实例的连接地址、密码
    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;
        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);
             
  • Jedis单连接(不推荐,单次超时后无法自动恢复)

    打开Eclipse客户端,创建一个Project,输入下述代码,然后根据注释提示修改代码。

    import redis.clients.jedis.Jedis;
    public class jedistest {
    public static void main(String[] args) {
    try {
         String host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";//实例的连接地址
         int port = 6379;
         Jedis jedis = new Jedis(host, port);
         //鉴权信息
         jedis.auth("password");//password
         String key = "redis";
         String value = "aliyun-redis";
         //select db默认为0
         jedis.select(1);
         //set一个key
         jedis.set(key, value);
         System.out.println("Set Key " + key + " Value: " + value);
         //get 设置进去的key
         String getvalue = jedis.get(key);
         System.out.println("Get Key " + key + " ReturnValue: " + getvalue);
         jedis.quit();
         jedis.close();
    catch (Exception e) {
     e.printStackTrace();
          
  • 运行上述Project,在Eclipse的控制台输出如下运行结果则表示您已成功连接至云数据库Redis。
    Set Key redis Value aliyun-redis
    Get Key redis ReturnValue aliyun-redis
    /* 分别将host和port的值替换为实例的连接地址、端口号。 */ $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com"; $port = 6379; /* 分别将user和pwd的值替换为实例的账号和密码 */ $user = "testaccount"; $pwd = "Rp829dlwa"; $redis = new Redis(); if ($redis->connect($host, $port) == false) { die($redis->getLastError()); if ($redis->auth($pwd) == false) { die($redis->getLastError()); /* 完成认证后可执行数据库操作,下述代码为您提供SET与GET的使用示例。 */ if ($redis->set("foo", "bar") == false) { die($redis->getLastError()); $value = $redis->get("foo"); echo $value; /* 分别将host和port的值替换为实例的连接地址、端口号。 */ $host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com"; $port = 6379; /* 分别将user和pwd的值替换为实例的账号和密码 */ $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()); /* 完成认证后可执行数据库操作,下述代码为您提供数据结构模块(如TairString)的使用示例。 */ 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"); import redis #分别将host和port的值替换为实例的连接地址、端口号。 host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com' port = 6379 #将pwd的值替换为实例的密码。 pwd = 'testaccount:Rp829dlwa' r = redis.StrictRedis(host=host, port=port, password=pwd) #连接建立后即可执行数据库操作,下述代码为您提供SET与GET的使用示例。 r.set('foo', 'bar'); print r.get('foo')
  • #!/usr/bin/env python
    #-*- coding: utf-8 -*-
    import redis
    #分别将host和port的值替换为实例的连接地址、端口号。
    host = 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com'
    port = 6379
    #将pwd的值替换为实例的密码。
    pwd = 'testaccount:Rp829dlwa'
    r = redis.StrictRedis(host=host, port=port, password=pwd)
    #连接建立后即可执行数据库操作,下述代码为您提供数据结构模块(如TairString)的使用示例。
    print(r.execute_command('CAS foo bar bzz'))
    print(r.execute_command('CAD foo bzz'))
    print(r.execute_command('EXSET foo 200 VER 1'))
        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'))
    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);
        /* 下述代码为您提供数据结构模块(如TairString)的使用方法 */
        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;
           读写分离架构,且需要执行切换或选择数据库的操作(即使用多数据库功能),您必须先将 
           cluster_compat_enable参数设置为 
           0(即关闭原生Redis Cluster语法兼容),然后重启客户端应用,否则将提示报错: 
            Multiple databases are not supported on this server; cannot switch to database。具体操作,请参见 
           设置实例参数
  • 执行下述命令,下载.net客户端。
    git clone https://github.com/ServiceStack/ServiceStack.Redis
  • 在.net 客户端中新建.net项目。
  • 添加客户端引用,引用文件在库文件的ServiceStack.Redis/lib/tests中。
  • 在新建的.net项目中输入如下代码,然后根据注释提示修改代码。更多信息,请参见接口说明
    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()
             // 将host的值替换为实例的连接地址
             string host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
             // 将password的值替换为实例的密码	 
             string password = "testaccount:Rp829dlwa";
             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://格式为密码@访问地址:端口*/
     RedisConfig.VerifyMasterConnections = false;//需要设置
     PooledRedisClientManager redisPoolManager = new PooledRedisClientManager(10/*连接池个数*/, 10/*连接池超时时间*/, testReadWriteHosts);
     for (int i = 0; i < 100; i++){
             IRedisClient redisClient = redisPoolManager.GetClient();//获取连接
             RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient;
             redisNativeClient.Client = null;//Redis不支持client setname,此处需要显示的把client对象置为null
             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)
             //单链接模式
             RedisClientTest();
             //连接池模式
             RedisPoolClientTest();
              
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using ServiceStack.Redis;
    namespace NetTestRedis {
    class Program {
        public static void RedisClientTest() {
            // 将host的值替换为实例的连接地址。
            string host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
            // 将password的值替换为实例的密码。
            string password = "testaccount:Rp829dlwa";
            RedisClient redisClient = new RedisClient(host, 6379, password);
    	// 下述代码为您提供数据结构模块(如TairString)的使用示例。
            System.Console.WriteLine("set : " + redisClient.Custom("set", "foo", "bal").Text);
            System.Console.WriteLine("CAS : " + redisClient.Custom("CAS", "foo", "bal", "bzz").Text);
            System.Console.WriteLine("CAD : " + redisClient.Custom("CAD", "foo", "bzz").Text);
            System.Console.WriteLine("EXSET : " + redisClient.Custom("EXSET", "foo", "200", "VER", "1").Text);
            try {
                System.Console.WriteLine("EXSET : " + redisClient.Custom("EXSET", "foo", "300", "VER", "10").Text);
            } catch (Exception ex) {
                Console.WriteLine("ERR : " + ex.ToString());
            var ret = redisClient.Custom("EXCAS", "foo", "300", "1");
            Console.Write("EXCAS : [");
            var values = ret.GetResults();
            // ["OK", "", version], The middle value is an empty string, meaningless when successful.
            foreach (string item in values) {
                Console.Write(item + " ");
            Console.Write("]");
        static void Main(string[] args) {
            //单链接模式
            RedisClientTest();
              
    var redis = require("redis"),
    // 分别设置实例的端口号和连接地址。
    client = redis.createClient(6379, "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com", {detect_buffers: true});
    //  设置实例的密码。
    client.auth("testaccount:Rp829dlwa", redis.print)
    // 写入数据。
    client.set("key", "OK");
    // 获取数据,返回String。
    client.get("key", function (err, reply) {
    console.log(reply.toString()); // print `OK`
    // 如果传入一个Buffer,返回也是一个Buffer。
    client.get(new Buffer("key"), function (err, reply) {
    console.log(reply.toString()); // print `<Buffer 4f 4b>`
    client.quit();
    var redis = require("redis");
    // 分别将host和port的值替换为实例的连接地址和端口。
    var client = redis.createClient({host : 'r-bp10noxlhcoim2****.redis.rds.aliyuncs.com', port : 6379});
    // 设置实例的密码。
    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`
    // 如果传入一个Buffer,返回也是一个Buffer。
    client.get(new Buffer("foo"), function (err, reply) {
        if (err) {
            console.log(err);
        } else {
            console.log(reply.toString()); // print `<Buffer 4f 4b>`
    // 下述代码为您提供数据结构模块(如TairString)的使用示例。
    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();
    读写分离架构,且需要执行切换或选择数据库的操作(即使用多数据库功能),您必须先将 cluster_compat_enable参数设置为 0(即关闭原生Redis Cluster语法兼容),然后重启客户端应用,否则将提示报错: RedisCommandException: Multiple databases are not supported on this server; cannot switch to database: 1。具体操作,请参见 设置实例参数
  • 下载并安装StackExchange.Redis
  • 根据提示修改下述示例代码。
    using StackExchange.Redis;
     // 分别设置实例的连接地址、端口号和密码。
     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
            // 分别设置实例的连接地址、端口号和密码。
    		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");
               
  • 关于如何获取Redis实例的连接地址和密码,请参见如何获取连接信息
  • 对于企业版(性能增强型)实例,您可以单击上方的企业版Tair示例页签,查看数据结构模块(如TairString)的使用示例。关于数据结构模块的相关介绍,请参见企业版(性能增强型)支持的新命令
  • ConfigurationOptions是StackExchange.Redis的核心,它被整个应用程序共享和重用,应该设置为单例,相关参数设置说明,请参见ConfigurationOptions
  • 由于GetDatabase()返回的对象是轻量级的,每次用的时候从ConnectionMultiplexer对象中获取即可。
    redisConn = getRedisConn();
     var db = redisConn.GetDatabase();
  • 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();
    client := redis.NewClient(&redis.Options{ // 替换为实例的连接地址和端口 Addr: "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379", // 替换为实例的密码 Password: "testaccount:Rp829dlwa", DB: 0, // use default DB // 下述代码为您提供SET与GET的使用示例。 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{
            // 替换为实例的连接地址和端口
    		Addr:     "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com:6379",
            // 替换为实例的密码
    		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)
    	// 下述代码为您提供数据结构模块(如TairString)的使用示例
    	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()
    
  •