ioredis 指南(JavaScript)
提示
来自deepseek解释
原文链接:https://redis.io/docs/latest/develop/clients/ioredis/
代码示例图例
以下代码示例展示了如何使用不同的编程语言和客户端库执行相同的操作:
- Redis CLI:Redis 的命令行界面
- C#(同步):StackExchange.Redis 同步客户端
- C#(异步):StackExchange.Redis 异步客户端
- Go:go-redis 客户端
- Java(同步 - Jedis):Jedis 同步客户端
- Java(异步 - Lettuce):Lettuce 异步客户端
- Java(响应式 - Lettuce):Lettuce 响应式/流式客户端
- JavaScript(Node.js):node-redis 客户端
- PHP:Predis 客户端
- Python:redis-py 客户端
- Rust(同步):redis-rs 同步客户端
- Rust(异步):redis-rs 异步客户端
每个代码示例都展示了跨不同语言的相同基本操作。具体语法和模式因语言和客户端库而异,但底层的 Redis 命令和行为保持一致。
ioredis 是 Redis 的 Node.js/JavaScript 客户端。 以下各节说明如何安装 ioredis 并将您的应用程序连接到 Redis 数据库。
由于 ioredis 被广泛使用,Redis 会积极维护和支持它,但对于新项目,我们建议使用较新的 Node.js 客户端 node-redis。如果您有兴趣将现有的 ioredis 项目转换为 node-redis,请参见从 ioredis 迁移。
ioredis 需要一个正在运行的 Redis 服务器。请参见此处获取 Redis 开源版的安装说明。
安装
要安装 ioredis,请运行:
npm install ioredis连接与测试
连接到 localhost 的 6379 端口。
可用语言: C, C#, Go, Java, JavaScript(Node.js), PHP, Python, Ruby, Rust
C
// 需要以下注释使示例可交互。
//%cflags:-lhiredis
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
// `redisContext` 类型表示与 Redis 服务器的连接。
// 这里我们连接到默认的主机和端口。
redisContext *c = redisConnect("127.0.0.1", 6379);
// 检查上下文是否为 null 或是否发生了特定错误。
if (c == NULL || c->err) {
if (c != NULL) {
printf("错误: %s\n", c->errstr);
// 处理错误
} else {
printf("无法分配 redis 上下文\n");
}
exit(1);
}
// 设置一个字符串键。
redisReply *reply = redisCommand(c, "SET foo bar");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 获取刚刚存储的键。
reply = redisCommand(c, "GET foo");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 关闭连接。
redisFree(c);
}C#(异步)
var muxer = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var db = muxer.GetDatabase();C#(同步)
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();Go
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // 无密码
DB: 0, // 使用默认 DB
Protocol: 2,
})
ctx := context.Background()Java(Lettuce)
RedisURI uri = RedisURI.Builder
.redis("localhost", 6379)
.build();
RedisClient client = RedisClient.create(uri);
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();Java(同步 - Jedis)
RedisClient jedis = new RedisClient("redis://localhost:6379");JavaScript(Node.js)- node-redis
import { createClient } from 'redis';
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();JavaScript(Node.js)- ioredis
import { Redis } from 'ioredis';
const redis = new Redis();PHP
<?php
require 'vendor/autoload.php';
use Predis\Client as PredisClient;
$r = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
]);Python
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)Ruby
require 'redis'
r = Redis.newRust(异步)
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("连接到 Redis 失败: {e}");
return;
}
}
},
Err(e) => {
println!("创建 Redis 客户端失败: {e}");
return;
}
};Rust(同步)
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_connection() {
Ok(conn) => conn,
Err(e) => {
println!("连接到 Redis 失败: {e}");
return;
}
}
},
Err(e) => {
println!("创建 Redis 客户端失败: {e}");
return;
}
};存储并检索一个简单的字符串。
可用语言: C, C#, Go, Java, JavaScript(Node.js), PHP, Python, Ruby, Rust
C
// 需要以下注释使示例可交互。
//%cflags:-lhiredis
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
// `redisContext` 类型表示与 Redis 服务器的连接。
// 这里我们连接到默认的主机和端口。
redisContext *c = redisConnect("127.0.0.1", 6379);
// 检查上下文是否为 null 或是否发生了特定错误。
if (c == NULL || c->err) {
if (c != NULL) {
printf("错误: %s\n", c->errstr);
// 处理错误
} else {
printf("无法分配 redis 上下文\n");
}
exit(1);
}
// 设置一个字符串键。
redisReply *reply = redisCommand(c, "SET foo bar");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 获取刚刚存储的键。
reply = redisCommand(c, "GET foo");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 关闭连接。
redisFree(c);
}C#(异步)
await db.StringSetAsync("foo", "bar");
string? fooResult = await db.StringGetAsync("foo");
Console.WriteLine(fooResult); // >>> barC#(同步)
db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo")); // >>> barGo
err := rdb.Set(ctx, "foo", "bar", 0).Err()
if err != nil {
panic(err)
}
val, err := rdb.Get(ctx, "foo").Result()
if err != nil {
panic(err)
}
fmt.Println("foo", val) // >>> foo barJava(Lettuce)
commands.set("foo", "bar");
String result = commands.get("foo");
System.out.println(result); // >>> barJava(同步 - Jedis)
String res1 = jedis.set("bike:1", "Deimos");
System.out.println(res1); // >>> OK
String res2 = jedis.get("bike:1");
System.out.println(res2); // >>> DeimosJavaScript(Node.js)- node-redis
await client.set('key', 'value');
const value = await client.get('key');
console.log(value);JavaScript(Node.js)- ioredis
await redis.set('key', 'value');
const value = await redis.get('key');
console.log(value); // >>> valuePHP
echo $r->set('foo', 'bar'), PHP_EOL;
// >>> OK
echo $r->get('foo'), PHP_EOL;
// >>> barPython
r.set('foo', 'bar')
# True
r.get('foo')
# barRuby
r.set 'foo', 'bar'
value = r.get('foo')
puts valueRust(异步)
if let Ok(res) = r.set("foo", "bar").await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 foo 时出错");
}
match r.get("foo").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("获取 foo 时出错: {e}");
return;
}
};Rust(同步)
if let Ok(res) = r.set("foo", "bar") {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 foo 时出错");
}
match r.get("foo") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("获取 foo 时出错: {e}");
return;
}
};存储并检索一个映射(哈希)。
可用语言: C, C#, Go, Java, JavaScript(Node.js), PHP, Python, Ruby, Rust
C
// 需要以下注释使示例可交互。
//%cflags:-lhiredis
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
// `redisContext` 类型表示与 Redis 服务器的连接。
// 这里我们连接到默认的主机和端口。
redisContext *c = redisConnect("127.0.0.1", 6379);
// 检查上下文是否为 null 或是否发生了特定错误。
if (c == NULL || c->err) {
if (c != NULL) {
printf("错误: %s\n", c->errstr);
// 处理错误
} else {
printf("无法分配 redis 上下文\n");
}
exit(1);
}
// 设置一个字符串键。
redisReply *reply = redisCommand(c, "SET foo bar");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 获取刚刚存储的键。
reply = redisCommand(c, "GET foo");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 关闭连接。
redisFree(c);
}C#(异步)
var hash = new HashEntry[] {
new HashEntry("name", "John"),
new HashEntry("surname", "Smith"),
new HashEntry("company", "Redis"),
new HashEntry("age", "29"),
};
await db.HashSetAsync("user-session:123", hash);
var hashFields = await db.HashGetAllAsync("user-session:123");
Console.WriteLine(String.Join("; ", hashFields));
// >>> name: John; surname: Smith; company: Redis; age: 29C#(同步)
var hash = new HashEntry[] {
new HashEntry("name", "John"),
new HashEntry("surname", "Smith"),
new HashEntry("company", "Redis"),
new HashEntry("age", "29"),
};
db.HashSet("user-session:123", hash);
var hashFields = db.HashGetAll("user-session:123");
Console.WriteLine(String.Join("; ", hashFields));
// >>> name: John; surname: Smith; company: Redis; age: 29Go
hashFields := []string{
"model", "Deimos",
"brand", "Ergonom",
"type", "Enduro bikes",
"price", "4972",
}
res1, err := rdb.HSet(ctx, "bike:1", hashFields).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> 4
res2, err := rdb.HGet(ctx, "bike:1", "model").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> Deimos
res3, err := rdb.HGet(ctx, "bike:1", "price").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> 4972
res4, err := rdb.HGetAll(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]Java(Lettuce)
import io.lettuce.core.*;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class ConnectBasicTest {
public void connectBasic() {
RedisURI uri = RedisURI.Builder
.redis("localhost", 6379)
.build();
RedisClient client = RedisClient.create(uri);
StatefulRedisConnection<String, String> connection = client.connect();
RedisCommands<String, String> commands = connection.sync();
commands.set("foo", "bar");
String result = commands.get("foo");
System.out.println(result); // >>> bar
connection.close();
client.shutdown();
}
}Java(同步 - Jedis)
Map<String, String> hash = new HashMap<>();
hash.put("name", "John");
hash.put("surname", "Smith");
hash.put("company", "Redis");
hash.put("age", "29");
Long res3 = jedis.hset("user-session:123", hash);
System.out.println(res3); // >>> 4
Map<String, String> res4 = jedis.hgetAll("user-session:123");
System.out.println(res4);
// >>> {name=John, surname=Smith, company=Redis, age=29}JavaScript(Node.js)- node-redis
await client.hSet('user-session:123', {
name: 'John',
surname: 'Smith',
company: 'Redis',
age: 29
})
let userSession = await client.hGetAll('user-session:123');
console.log(JSON.stringify(userSession, null, 2));JavaScript(Node.js)- ioredis
await redis.hset('user-session:123', {
name: 'John',
surname: 'Smith',
company: 'Redis',
age: 29
});
const userSession = await redis.hgetall('user-session:123');
console.log(JSON.stringify(userSession, null, 2));
/* >>>
{
"surname": "Smith",
"name": "John",
"company": "Redis",
"age": "29"
}
*/PHP
$r->hset('user-session:123', 'name', 'John');
$r->hset('user-session:123', 'surname', 'Smith');
$r->hset('user-session:123', 'company', 'Redis');
$r->hset('user-session:123', 'age', 29);
echo var_export($r->hgetall('user-session:123')), PHP_EOL;
/* >>>
array (
'name' => 'John',
'surname' => 'Smith',
'company' => 'Redis',
'age' => '29',
)
*/Python
import redis
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
r.set('foo', 'bar')
# True
r.get('foo')
# bar
r.hset('user-session:123', mapping={
'name': 'John',
"surname": 'Smith',
"company": 'Redis',
"age": 29
})
# True
r.hgetall('user-session:123')
# {'surname': 'Smith', 'name': 'John', 'company': 'Redis', 'age': '29'}
r.close()Ruby
require 'redis'
r = Redis.new
r.set 'foo', 'bar'
value = r.get('foo')
puts value
r.hset 'user-session:123', 'name', 'John'
r.hset 'user-session:123', 'surname', 'Smith'
r.hset 'user-session:123', 'company', 'Redis'
r.hset 'user-session:123', 'age', 29
hash_value = r.hgetall('user-session:123')
puts hash_value
r.close()Rust(异步)
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields).await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 bike:1 时出错");
}
match r.hget("bike:1", "model").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("获取 bike:1 model 时出错: {e}");
return;
}
}
match r.hget("bike:1", "price").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("获取 bike:1 price 时出错: {e}");
return;
}
}
match r.hgetall("bike:1").await {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("获取 bike:1 时出错: {e}");
return;
}Rust(同步)
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields) {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 bike:1 时出错");
}
match r.hget("bike:1", "model") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("获取 bike:1 model 时出错: {e}");
return;
}
}
match r.hget("bike:1", "price") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("获取 bike:1 price 时出错: {e}");
return;
}
}
match r.hgetall("bike:1") {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("获取 bike:1 时出错: {e}");
return;
}
}完成连接使用后,使用 client.quit() 关闭它。
可用语言: C, C#, Go, Java, JavaScript(Node.js), PHP, Python, Ruby, Rust
C
// 需要以下注释使示例可交互。
//%cflags:-lhiredis
#include <stdio.h>
#include <stdlib.h>
#include <hiredis/hiredis.h>
int main() {
// `redisContext` 类型表示与 Redis 服务器的连接。
// 这里我们连接到默认的主机和端口。
redisContext *c = redisConnect("127.0.0.1", 6379);
// 检查上下文是否为 null 或是否发生了特定错误。
if (c == NULL || c->err) {
if (c != NULL) {
printf("错误: %s\n", c->errstr);
// 处理错误
} else {
printf("无法分配 redis 上下文\n");
}
exit(1);
}
// 设置一个字符串键。
redisReply *reply = redisCommand(c, "SET foo bar");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 获取刚刚存储的键。
reply = redisCommand(c, "GET foo");
printf("回复: %s\n", reply->str);
freeReplyObject(reply);
// 关闭连接。
redisFree(c);
}C#(异步)
using StackExchange.Redis;
public class AsyncLandingExample
{
public async Task Run()
{
var muxer = await ConnectionMultiplexer.ConnectAsync("localhost:6379");
var db = muxer.GetDatabase();
await db.StringSetAsync("foo", "bar");
string? fooResult = await db.StringGetAsync("foo");
Console.WriteLine(fooResult); // >>> bar
var hash = new HashEntry[] {
new HashEntry("name", "John"),
new HashEntry("surname", "Smith"),
new HashEntry("company", "Redis"),
new HashEntry("age", "29"),
};
await db.HashSetAsync("user-session:123", hash);
var hashFields = await db.HashGetAllAsync("user-session:123");
Console.WriteLine(String.Join("; ", hashFields));
// >>> name: John; surname: Smith; company: Redis; age: 29
}
}C#(同步)
using StackExchange.Redis;
public class SyncLandingExample
{
public void Run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
db.StringSet("foo", "bar");
Console.WriteLine(db.StringGet("foo")); // >>> bar
var hash = new HashEntry[] {
new HashEntry("name", "John"),
new HashEntry("surname", "Smith"),
new HashEntry("company", "Redis"),
new HashEntry("age", "29"),
};
db.HashSet("user-session:123", hash);
var hashFields = db.HashGetAll("user-session:123");
Console.WriteLine(String.Join("; ", hashFields));
// >>> name: John; surname: Smith; company: Redis; age: 29
}
}Go
rdb.Close()Java(Lettuce)
connection.close();
client.shutdown();Java(同步 - Jedis)
jedis.close();JavaScript(Node.js)- node-redis
await client.quit();JavaScript(Node.js)- ioredis
redis.disconnect();PHP
<?php
require 'vendor/autoload.php';
use Predis\Client as PredisClient;
$r = new PredisClient([
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'database' => 0,
]);
echo $r->set('foo', 'bar'), PHP_EOL;
// >>> OK
echo $r->get('foo'), PHP_EOL;
// >>> bar
$r->hset('user-session:123', 'name', 'John');
$r->hset('user-session:123', 'surname', 'Smith');
$r->hset('user-session:123', 'company', 'Redis');
$r->hset('user-session:123', 'age', 29);
echo var_export($r->hgetall('user-session:123')), PHP_EOL;
/* >>>
array (
'name' => 'John',
'surname' => 'Smith',
'company' => 'Redis',
'age' => '29',
)
*/Python
r.close()Ruby
r.close()Rust(异步)
mod tests {
use redis::AsyncCommands;
async fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_multiplexed_async_connection().await {
Ok(conn) => conn,
Err(e) => {
println!("连接到 Redis 失败: {e}");
return;
}
}
},
Err(e) => {
println!("创建 Redis 客户端失败: {e}");
return;
}
};
if let Ok(res) = r.set("foo", "bar").await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 foo 时出错");
}
match r.get("foo").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("获取 foo 时出错: {e}");
return;
}
};
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields).await {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 bike:1 时出错");
}
match r.hget("bike:1", "model").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("获取 bike:1 model 时出错: {e}");
return;
}
}
match r.hget("bike:1", "price").await {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("获取 bike:1 price 时出错: {e}");
return;
}
}
match r.hgetall("bike:1").await {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("获取 bike:1 时出错: {e}");
return;
}
}
}
}Rust(同步)
mod landing_tests {
use redis::Commands;
fn run() {
let mut r = match redis::Client::open("redis://127.0.0.1") {
Ok(client) => {
match client.get_connection() {
Ok(conn) => conn,
Err(e) => {
println!("连接到 Redis 失败: {e}");
return;
}
}
},
Err(e) => {
println!("创建 Redis 客户端失败: {e}");
return;
}
};
if let Ok(res) = r.set("foo", "bar") {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 foo 时出错");
}
match r.get("foo") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> bar
},
Err(e) => {
println!("获取 foo 时出错: {e}");
return;
}
};
let hash_fields = [
("model", "Deimos"),
("brand", "Ergonom"),
("type", "Enduro bikes"),
("price", "4972"),
];
if let Ok(res) = r.hset_multiple("bike:1", &hash_fields) {
let res: String = res;
println!("{res}"); // >>> OK
} else {
println!("设置 bike:1 时出错");
}
match r.hget("bike:1", "model") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> Deimos
},
Err(e) => {
println!("获取 bike:1 model 时出错: {e}");
return;
}
}
match r.hget("bike:1", "price") {
Ok(res) => {
let res: String = res;
println!("{res}"); // >>> 4972
},
Err(e) => {
println!("获取 bike:1 price 时出错: {e}");
return;
}
}
match r.hgetall("bike:1") {
Ok(res) => {
let res: Vec<(String, String)> = res;
for (key, value) in res {
println!("{key}: {value}");
}
// >>> model: Deimos
// >>> brand: Ergonom
// >>> type: Enduro bikes
// >>> price: 4972
},
Err(e) => {
println!("获取 bike:1 时出错: {e}");
return;
}
}
}
}