527
阿裏雲
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-阿裏雲