连接实例
连接实例
1. Java
- 运行前准备: 下载客户端 Jedis
示例代码
import redis.clients.jedis.Jedis; public class HelloRedis { public static void main(String[] args) { try { /**以下参数分别为您的 Redis 实例 IP、端口号、密码*/ String host = "your ip"; int port = 6379; String password = "your password"; //连接Redis Jedis jedis = new Jedis(host, port); //鉴权 jedis.auth(password); /**接下来可以开始操作 Redis 实例,可以参考 https://github.com/xetorthio/jedis */ //设置 Key jedis.set("redis", "hello world"); //获取 Key System.out.println(jedis.get("redis")); //关闭退出 jedis.quit(); jedis.close(); } catch (Exception e) { e.printStackTrace(); } } }
运行结果
Hello world
2. Python
- 运行前准备: 下载并安装redis-py
示例代码
!/usr/bin/env python #-*- coding: utf-8 -*- import redis #以下参数分别为您的 Redis 实例的IP、端口号 和密码 host = 'Your Ip' port = 6379 pwd = 'Your Password' r = redis.StrictRedis(host=host, port=port, password=pwd) #连接建立后就可以进行数据库操作,详情请参见https://github.com/andymccurdy/redis-py r.set('redis', 'yovole'); print r.get('redis')
运行结果
yovole
3. C
- 运行前准备: 下载并安装hirredis
示例代码
#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 < 3) { printf("Usage: example 127.0.0.1 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 = 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", "redis", "hello world"); printf("SET: %s\n", reply->str); freeReplyObject(reply); /* Try a GET */ reply = redisCommand(c,"GET redis"); printf("GET redis: %s\n", reply->str); freeReplyObject(reply); /* Disconnects and frees the context */ redisFree(c); return 0; }
运行结果
./example 127.0.0.1 6379 passpord AUTH: OK PING: PONG SET: OK GET redis: hello word
4. Go
- 运行前准备: 下载并安装Go-redis
示例代码
package mainimport( "fmt" "redis" "log" )func main() { const host="your ip" const port=6379 const pass="your passowrd" // 连接 Redis 服务器并授权密码 spec := redis.DefaultSpec().Host(host).Port(port).Password(pass); client, err := redis.NewSynchClientWithSpec(spec) if err != nil { // 是否连接出错 log.Println("error on connect redis server") return } newvalue :=[]byte("hello word"); err=client.Set("redis",newvalue); if err != nil { // 设置值出错 log.Println(err) return } value, err := client.Get("redis") // 取值 if err != nil { log.Println(err) return } fmt.Println("redis value is:",fmt.Sprintf("%s", value))
运行结果
Redis value is:hello word
5. .Net
- 运行前准备: 下载并安装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() { string host = "your ip";/*访问host地址*/ string password = "your password";/*密码*/ RedisClient redisClient = new RedisClient(host, 6379, password); string key = "test-key"; string value = "test"; redisClient.Set(key, value); string listKey = "test-key-list"; System.Console.WriteLine("set key " + key + " value " + value); string getValue = System.Text.Encoding.Default.GetString(redisClient.Get(key)); System.Console.WriteLine("get key " + key + " value "+ 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 < 1; i++){ IRedisClient redisClient = redisPoolManager.GetClient();//获取连接 RedisNativeClient redisNativeClient = (RedisNativeClient)redisClient; redisNativeClient.Client = null;//ApsaraDB for Redis不支持client setname所以这里需要显示的把client对象置为null try { string key = "test-key1111"; string value = "test-key-value1111"; redisClient.Set(key, value); string listKey = "test-key-list"; redisClient.AddItemToList(listKey, value); System.Console.WriteLine("set key " + key + " value " + value); string getValue = redisClient.GetValue(key); System.Console.WriteLine("get key "+ key + " value " + getValue); redisClient.Dispose();// }catch (Exception e) { System.Console.WriteLine(e.Message); } } System.Console.Read(); } static void Main(string[] args) { //单链接模式 RedisClientTest(); //连接池模式 RedisPoolClientTest(); } } }
运行结果
set key test-key value test get key test-key value test set key test-key1111value test-key-value1111 get key test-key1111value test-key-value1111
6. PHP
- 运行前准备: 下载并安装;phpredis
示例代码
<?php /* 这里替换为连接的实例连接地址和端口 */ $host = "your ip"; $port = 6379; /* 这里替换为实例的密码 */ $pwd = "your 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("redis", "hello world") == false) { die($redis->getLastError()); } $value = $redis->get("redis"); echo $value; ?>
运行结果
hello world
7. Node.js
运行前准备: 执行以下命令,安装 node-redis:
npm install hiredis redis
示例代码
var redis = require("redis"); var host = "your ip", port = "6379", pwd = "your password"; //连接 Redis var client = redis.createClient(port, host, {detect_buffers: true}); client.on("error", function(error) { console.log(error); });//鉴权 client.auth(pwd); // 写入数据 client.set("redis", "OK"); // 获取数据,返回String client.get("key", function (err, reply) { console.log(reply.toString()); }); // 如果传入一个Buffer,返回也是一个Buffer client.get(new Buffer("redis"), function (err, reply) { console.log(reply.toString()); }); client.quit();
运行结果
OK <Buffer 4f 4b>