云数据库Redis与原生Redis完全兼容,连接数据库的方式也基本相同,您可以根据自身应用特点选用任何兼容Redis协议的客户端程序。本文列举一些常见的客户端程序的代码示例,帮助您快速连接。
前提条件
根据客户端程序的部署位置,完成下述操作:
客户端程序部署位置 |
需完成的操作 |
ECS实例(推荐)
|
- 确保ECS实例与Redis实例属于同一专有网络(即实例基本信息中的专有网络ID一致)。
- 获取ECS实例的内网IP地址。具体操作,请参见查询ECS实例的IP地址。
- 将ECS实例的内网IP地址添加至Redis实例的白名单中。具体操作,请参见设置IP白名单。
|
本地 |
- Redis实例默认仅提供内网连接地址,通过公网连接时您需要手动申请公网连接地址。具体操作,请参见申请公网连接地址。
- 在本地客户端所属的设备上执行curl ipinfo.io |grep ip获取其公网IP地址,返回示例如下:

说明 如果本地客户端所属设备为Windows操作系统,您可以访问 淘宝IP地址库获取公网地址。
- 将本地客户端的公网IP地址添加至Redis实例的白名单中。具体操作,请参见设置IP白名单。
|
注意事项
- 如果您的Redis实例为集群架构或读写分离架构,实例默认会提供Proxy(代理)节点的连接地址,连接方式与连接标准架构的Redis实例相同。
说明 集群架构的实例通过
直连地址连接时,连接方式与连接开源Redis Cluster相同。
- 如果实例开启了专有网络免密访问,同一专有网络下的客户端程序无需设置密码即可连接Redis实例。
如何获取连接信息
在使用客户端程序连接Redis实例时,通常您需要获取以下信息并设置在代码中:
需获取的信息 |
获取方式 |
实例的连接地址 |
Redis实例支持多种连接地址,推荐使用专有网络连接,可获得更高的安全性和更低的网络延迟。更多信息,请参见查看连接地址。
|
端口号 |
端口号默认为6379,您也可以自定义端口号。具体操作,请参见修改连接端口。
|
实例的账号(部分客户端程序无需设置) |
Redis实例默认会创建一个以实例ID命名的账号(例如r-bp10noxlhcoim2****),您也可以创建一个新的账号并赋予权限。更多信息,请参见创建与管理账号。
|
账号的密码 |
根据选取账号的不同,密码的填写格式有一定区别:
- 默认账号(即以实例ID命名的账号):直接填写密码即可。
- 新创建的账号:密码格式为
<user>:<password> 。例如自定义账号为testaccount ,密码为Rp829dlwa ,密码需填写为testaccount:Rp829dlwa 。
|
Jedis客户端
- 下载并安装Jedis客户端。具体操作,请参见Jedis使用说明。
- 根据业务需求选择连接方式。
- JedisPool连接池连接(推荐)
- 打开Eclipse客户端,创建一个Project并配置pom文件,具体内容如下:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
- 在Project中输入下述代码添加相关应用。
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
- 根据Jedis客户端版本,在Project中输入下述代码,然后根据注释提示修改代码。
- Jedis 2.7.2版本
JedisPoolConfig config = new JedisPoolConfig();
//最大空闲连接数,需自行评估,不超过Redis实例的最大连接数
config.setMaxIdle(200);
//最大连接数,需自行评估,不超过Redis实例的最大连接数
config.setMaxTotal(300);
config.setTestOnBorrow(false);
config.setTestOnReturn(false);
String host = "*.aliyuncs.com";
String password = "密码";
JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
Jedis jedis = null;
try {
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();
- Jedis 2.6或Jedis 2.5版本
JedisPoolConfig config = new JedisPoolConfig();
//最大空闲连接数,需自行评估,不超过Redis实例的最大连接数
config.setMaxIdle(200);
//最大连接数,需自行评估,不超过Redis实例的最大连接数
config.setMaxTotal(300);
config.setTestOnBorrow(false);
config.setTestOnReturn(false);
String host = "*.aliyuncs.com";
String password = "密码";
JedisPool pool = new JedisPool(config, host, 6379, 3000, password);
Jedis jedis = null;
boolean broken = false;
try {
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 = "xx.kvstore.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
警告 在使用Jedis的过程中,如果设置了一些不合理的参数或错误使用某些功能可能会引起报错,关于如何排查,请参见
Jedis常见异常汇总。
Lettuce客户端
Lettuce支持完整Redis API的同步和异步通信使用。由于Lettuce客户端在请求多次请求超时后,不再自动重连,当云数据库Redis因故障等因素导致代理或者数据库节点发生切换时,可能出现连接超时导致无法重连。为避免此类风险,推荐您使用Jedis客户端。
更多信息,请参见Lettuce。
TairJedis客户端
TairJedis是阿里云基于Jedis开发的Redis企业版专用客户端,除了Jedis的原有功能,还支持Redis企业版数据结构模块包含的命令。
更多信息,请参见tairjedis-sdk。
PhpRedis客户端
- 下载并安装PhpRedis客户端。具体操作,请参见PhpRedis使用说明。
- 在PHP编辑器中输入下述代码,然后根据注释提示修改代码。
说明 关于如何获取Redis实例的连接地址、账号和密码,请参见
如何获取连接信息。
<?php
/* 这里替换为连接的实例连接地址和端口 */
$host = "r-bp10noxlhcoim2****.redis.rds.aliyuncs.com";
$port = 6379;
/* 这里替换为实例ID和实例的密码 */
$user = "test_username";
$pwd = "test_password";
$redis = new Redis();
if ($redis->connect($host, $port) == false) {
die($redis->getLastError());
}
if ($redis->auth($pwd) == false) {
die($redis->getLastError());
}
/* 认证后就可以进行数据库操作,详情请参见https://github.com/phpRedis/phpredis */
if ($redis->set("foo", "bar") == false) {
die($redis->getLastError());
}
$value = $redis->get("foo");
echo $value;
?>
- 执行上述代码即可完成连接。
redis-py客户端
- 下载并安装redis-py客户端。具体操作,请参见redis-py使用说明。
- 在Python编辑器中输入下述代码,然后根据注释提示修改代码。
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import redis
#替换host的值为实例的连接地址,替换port的值为端口。
host = 'localhost'
port = 6379
#这里替换为实例password
pwd = 'test_password'
r = redis.StrictRedis(host=host, port=port, password=pwd)
#连接建立后就可以进行数据库操作,详情请参见https://github.com/andymccurdy/redis-py
r.set('foo', 'bar');
print r.get('foo')
- 执行上述代码即可完成连接。
C或C++客户端
- 执行下述命令,下载并编译安装C客户端。
git clone https://github.com/redis/hiredis.git
cd hiredis
make
sudo make install
- 在C或C++编辑器中输入下述代码,然后根据注释提示修改代码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
unsigned int j;
redisContext *c;
redisReply *reply;
if (argc < 4) {
printf("Usage: example xxx.kvstore.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;
}
- 编译上述代码。
gcc -o example -g example.c -I /usr/local/include/hiredis -lhiredis
- 测试运行,完成连接。
example xxx.kvstore.aliyuncs.com 6379 instance_id password
.net客户端
警告 如果您的Redis实例为
集群架构或
读写分离架构,且需要执行切换或选择数据库的操作(即使用多数据库功能),您必须先将
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()
{
string host = "127.0.0.1";/*访问host地址*/
string password = "password";/*密码*/
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;//ApsaraDB for Redis不支持client setname所以这里需要显示的把client对象置为null
try
{
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();
}
}
}
node-redis客户端
- 下载并安装node-redis。
npm install hiredis redis
- 在node-redis客户端中输入下述代码,然后根据注释提示修改代码。
var redis = require("redis"),
client = redis.createClient(<port>, <"host">, {detect_buffers: true});
client.auth("password", redis.print)
参数说明:
- <port>:Redis实例的服务端口,默认为6379。
- <"host">:Redis实例的连接地址。
配置示例:
var redis = require("redis"),
client = redis.createClient(6379, "r-abcdefg.redis.rds.aliyuncs.com", {detect_buffers: true});
client.auth("password", redis.print)
- 执行上述代码完成连接。
- 使用云数据库Redis。
// 写入数据
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();
C#客户端StackExchange.Redis
警告 如果您的Redis实例为
集群架构或
读写分离架构,且需要执行切换或选择数据库的操作(即使用多数据库功能),您必须先将
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;
- 初始化ConnectionMultiplexer。
ConnectionMultiplexer是StackExchange.Redis的核心,它被整个应用程序共享和重用,应该设置为单例,它的初始化如下:
// redis config
private static ConfigurationOptions configurationOptions = ConfigurationOptions.Parse("127.0.0.1:6379,password=xxx,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;
}
- 由于GetDatabase()返回的对象是轻量级的,每次用的时候从ConnectionMultiplexer对象中获取即可。
redisConn = getRedisConn();
var db = redisConn.GetDatabase();
- 通过客户端程序操作Redis数据库。
说明 下文列出常见数据接口的demo示例,和原生API略有不同。
- String
//set get
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]);
- Hash
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
//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
//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 );
- Sorted Set
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();
在文档使用中是否遇到以下问题
更多建议
匿名提交