云数据库Redis与原生Redis完全兼容,连接数据库的方式也基本相同,您可以根据自身应用特点选用任何兼容Redis协议的客户端程序。本文列举一些常见的客户端程序的代码示例,帮助您快速连接。
根据客户端程序的部署位置,完成下述操作: 实例的账号(部分客户端程序无需设置) Redis实例默认会创建一个以实例ID命名的账号(例如r-bp10noxlhcoim2****),您也可以创建一个新的账号并赋予权限。更多信息,请参见 创建与管理账号 。 账号的密码根据选取账号的不同,密码的填写格式有一定区别:
<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);
打开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();
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
。具体操作,请参见
设置实例参数。
git clone 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() // 将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
。具体操作,请参见 设置实例参数。
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");
redisConn = getRedisConn(); var db = redisConn.GetDatabase();
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 -> ", 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()