Redis客户端连接__连接实例_快速入门_云数据库 Redis 版-阿里云
Redis 客户端连接
由于云数据库 Redis 提供的数据库服务与原生的数据库服务完全兼容,连接数据库的方式也基本类似。任何兼容 Redis 协议的客户端都可以访问阿里云 ApsaraDB for Redis 服务,您可以根据自身应用特点选用任何 Redis 客户端。
注意:云数据库 Redis 版仅支持阿里云内网访问,不支持外网访问,即只有在同节点的 ECS上安装 Redis 客户端才能与云数据库建立连接并进行数据操作。
Redis 的客户端请参考 https://redis.io/clients 。
Jedis 客户端
Jedis 下载
点击 参考地址。
Jedis 单连接示例
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();
}
}
}
JedisPool 连接池示例
配置文件
用户根据自己选择的客户端版本配置pom配置文件,配置如下:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
需要添加的引用
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-2.7.2示例
JedisPoolConfig config = new JedisPoolConfig();
//最大空闲连接数, 应用自己评估,不要超过ApsaraDB for Redis每个实例最大的连接数
config.setMaxIdle(200);
//最大连接数, 应用自己评估,不要超过ApsaraDB for 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();
//最大空闲连接数, 应用自己评估,不要超过ApsaraDB for Redis每个实例最大的连接数
config.setMaxIdle(200);
//最大连接数, 应用自己评估,不要超过ApsaraDB for 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);
}
}
phpredis 客户端
phpredis下载
点击 参考地址。
连接代码示例
<?php
/* 这里替换为连接的实例host和port */
$host = "localhost";
$port = 6379;
/* 这里替换为实例id和实例password */
$user = "test_username";
$pwd = "test_password";
$redis = new Redis();
if ($redis->connect($host, $port) == false) {
die($redis->getLastError());
}
/* user:password 拼接成AUTH的密码 */
if ($redis->auth($user . ":" . $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下载
点击 参考地址。
连接代码示例
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import redis
#这里替换为连接的实例host和port
host = 'localhost'
port = 6379
#这里替换为实例id和实例password
user = 'test_username'
pwd = 'test_password'
#连接时通过password参数指定AUTH信息,由user,pwd通过":"拼接而成
r = redis.StrictRedis(host=host, port=port, password=user+':'+pwd)
#连接建立后就可以进行数据库操作,详情文档参考https://github.com/andymccurdy/redis-py
r.set('foo', 'bar');
print r.get('foo')
C/C++客户端
下面是一个 C/C++ 程序使用 ApsaraDB for Redis 的步骤及简单例子。
- 下载编译安装C客户端。
git clone https://github.com/redis/hiredis.git
cd hiredis
make
sudo make install
编写测试代码。
#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 passwordn");
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: %sn", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis contextn");
}
exit(1);
}
/* AUTH */
reply = redisCommand(c, "AUTH %s:%s", instance_id, password);
printf("AUTH: %sn", reply->str);
freeReplyObject(reply);
/* PING server */
reply = redisCommand(c,"PING");
printf("PING: %sn", reply->str);
freeReplyObject(reply);
/* Set a key */
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
printf("SET: %sn", 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): %sn", reply->str);
freeReplyObject(reply);
/* Try a GET and two INCR */
reply = redisCommand(c,"GET foo");
printf("GET foo: %sn", reply->str);
freeReplyObject(reply);
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lldn", reply->integer);
freeReplyObject(reply);
/* again ... */
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lldn", 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) %sn", 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客户端
下面是一个 .net 程序使用 ApsaraDB for Redis 的步骤及简单例子。
- 下载及使用.net客户端。
git clone https://github.com/ServiceStack/ServiceStack.Redis
- 新建 .net 项目。
添加客户端引用,引用文件在库文件的 ServiceStack.Redis/lib/tests 中。
测试代码示例:
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 = "fb92bf2e0abf11e5:123456128a1A";/*实例id:密码*/
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://:fb92bf2e0abf11e5:1234561178a1A@127.0.0.1:6379"/*redis://:实例id:密码@访问地址:端口*/
};
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();
}
}
}
详细的接口用法请参见 https://github.com/ServiceStack/ServiceStack.Redis 。
node-redis 客户端
安装 node-redis。
npm install hiredis redis
连接 ApsaraDB for Redis。
var redis = require("redis"),
client = redis.createClient({detect_buffers: true});
client.auth("instanceid:password", redis.print)
使用 ApsaraDB for 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();
最后更新:2016-12-16 17:39:23
上一篇:
DMS 登录云数据库__连接实例_快速入门_云数据库 Redis 版-阿里云
下一篇:
Redis-cli连接__连接实例_快速入门_云数据库 Redis 版-阿里云
创建实时同步作业__快速入门_数据传输-阿里云
请求状态__常用指标_使用手册_性能测试-阿里云
考试形式和试卷结构__弹性计算认证(ACP级)_如何获得专业技术认证?_专业技术认证-阿里云
AssumedRoleUser__数据类型_STS API文档_访问控制-阿里云
怎样为一个子用户授予只读访问RDS的权限___云数据库(RDS)授权问题_授权常见问题_访问控制-阿里云
用户使用流程__概述_用户指南_容器服务-阿里云
SetVServerGroupAttribute__VServerGroup相关API_API 参考_负载均衡-阿里云
清理RDS实例日志__实例管理_API 参考_云数据库 RDS 版-阿里云
高性能__产品优势_产品简介_云数据库 RDS 版-阿里云
Android播放器SDK说明__SDK文档及下载_API及SDK_视频直播-阿里云
相关内容
常见错误说明__附录_大数据计算服务-阿里云
发送短信接口__API使用手册_短信服务-阿里云
接口文档__Android_安全组件教程_移动安全-阿里云
运营商错误码(联通)__常见问题_短信服务-阿里云
设置短信模板__使用手册_短信服务-阿里云
OSS 权限问题及排查__常见错误及排除_最佳实践_对象存储 OSS-阿里云
消息通知__操作指南_批量计算-阿里云
设备端快速接入(MQTT)__快速开始_阿里云物联网套件-阿里云
查询API调用流量数据__API管理相关接口_API_API 网关-阿里云
使用STS访问__JavaScript-SDK_SDK 参考_对象存储 OSS-阿里云