Appearance
Redis 作为内存中数据结构存储快速入门指南
了解如何使用基本的 Redis 数据类型
本快速入门指南向您展示如何:
- 开始使用 Redis
- 在 Redis 的 key 下存储数据
- 使用 Redis 中的键检索数据
- 扫描键空间以查找与特定模式匹配的键
本文中的示例是指简单的自行车清单。
设置
开始使用 Redis 的最简单方法是使用 Redis Cloud:
- 创建一个免费帐户。
- 按照说明创建免费数据库。
您也可以按照安装指南在本地计算机上安装 Redis。
连接
第一步是连接到 Redis。您可以在此文档站点的 connection 部分找到有关连接选项的更多详细信息。以下示例显示了如何连接到在 localhost (-h 127.0.0.1) 上运行并侦听默认端口 (-p 6379) 的 Redis 服务器:
bash
redis-cli -h 127.0.0.1 -p 6379
python
r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)
java
// UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
JedisPooled jedis = new JedisPooled("localhost", 6379);
js
const client = createClient();
client.on('error', err => console.log('Redis Client Error', err));
await client.connect();
csharp
var redis = ConnectionMultiplexer.Connect("localhost:6379");
var db = redis.GetDatabase();
var ft = db.FT();
var json = db.JSON();
提示
您可以从 Redis Cloud 数据库配置页面复制并粘贴连接详细信息。以下是托管在 AWS 区域us-east-1
中并侦听端口 16379 的云数据库的示例连接字符串:redis-16379.c283.us-east-1-4.ec2.cloud.redislabs.com:16379
。连接字符串的格式为host:port
.您还必须复制并粘贴云数据库的用户名和密码,然后将凭证传递给您的客户端或在建立连接后使用 AUTH 命令。
存储和检索数据
Redis 代表远程词典服务器。您可以使用与本地编程环境中相同的数据类型,但在 Redis 的服务器端使用。
与字节数组类似,Redis 字符串存储字节序列,包括文本、序列化对象、计数器值和二进制数组。以下示例演示如何设置和获取字符串值:
bash
SET bike:1 "Process 134"
GET bike:1
python
res = r.set("bike:1", "Process 134")
print(res)
# >>> True
res = r.get("bike:1")
print(res)
# >>> "Process 134"
js
await client.set('bike:1', 'Process 134');
const value = await client.get('bike:1');
console.log(value);
// returns 'Process 134'
java
String status = jedis.set("bike:1", "Process 134");
if ("OK".equals(status)) System.out.println("Successfully added a bike.");
String value = jedis.get("bike:1");
if (value != null) System.out.println("The name of the bike is: " + value + ".");
go
err := rdb.Set(ctx, "bike:1", "Process 134", 0).Err()
if err != nil {
panic(err)
}
fmt.Println("OK")
value, err := rdb.Get(ctx, "bike:1").Result()
if err != nil {
panic(err)
}
fmt.Printf("The name of the bike is %s", value)
csharp
bool status = db.StringSet("bike:1", "Process 134");
if (status)
Console.WriteLine("Successfully added a bike.");
var value = db.StringGet("bike:1");
if (value.HasValue)
Console.WriteLine("The name of the bike is: " + value + ".");
哈希相当于字典(字典或哈希映射)。此外,您可以使用哈希来表示普通对象并存储计数器分组。以下示例说明如何设置和访问对象的字段值:
bash
> HSET bike:1 model Deimos brand Ergonom type 'Enduro bikes' price 4972
(integer) 4
> HGET bike:1 model
"Deimos"
> HGET bike:1 price
"4972"
> HGETALL bike:1
1) "model"
2) "Deimos"
3) "brand"
4) "Ergonom"
5) "type"
6) "Enduro bikes"
7) "price"
8) "4972"
python
res1 = r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
print(res1)
# >>> 4
res2 = r.hget("bike:1", "model")
print(res2)
# >>> 'Deimos'
res3 = r.hget("bike:1", "price")
print(res3)
# >>> '4972'
res4 = r.hgetall("bike:1")
print(res4)
# >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'}
js
const res1 = await client.hSet(
'bike:1',
{
'model': 'Deimos',
'brand': 'Ergonom',
'type': 'Enduro bikes',
'price': 4972,
}
)
console.log(res1) // 4
const res2 = await client.hGet('bike:1', 'model')
console.log(res2) // 'Deimos'
const res3 = await client.hGet('bike:1', 'price')
console.log(res3) // '4972'
const res4 = await client.hGetAll('bike:1')
console.log(res4)
/*
{
brand: 'Ergonom',
model: 'Deimos',
price: '4972',
type: 'Enduro bikes'
}
*/
java
Map<String, String> bike1 = new HashMap<>();
bike1.put("model", "Deimos");
bike1.put("brand", "Ergonom");
bike1.put("type", "Enduro bikes");
bike1.put("price", "4972");
Long res1 = jedis.hset("bike:1", bike1);
System.out.println(res1); // 4
String res2 = jedis.hget("bike:1", "model");
System.out.println(res2); // Deimos
String res3 = jedis.hget("bike:1", "price");
System.out.println(res3); // 4972
Map<String, String> res4 = jedis.hgetAll("bike:1");
System.out.println(res4); // {type=Enduro bikes, brand=Ergonom, price=4972, model=Deimos}
go
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
cmdReturn := rdb.HGetAll(ctx, "bike:1")
res4, err := cmdReturn.Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> map[brand:Ergonom model:Deimos price:4972 type:Enduro bikes]
type BikeInfo struct {
Model string `redis:"model"`
Brand string `redis:"brand"`
Type string `redis:"type"`
Price int `redis:"price"`
}
var res4a BikeInfo
if err := cmdReturn.Scan(&res4a); err != nil {
panic(err)
}
fmt.Printf("Model: %v, Brand: %v, Type: %v, Price: $%v\n",
res4a.Model, res4a.Brand, res4a.Type, res4a.Price)
// >>> Model: Deimos, Brand: Ergonom, Type: Enduro bikes, Price: $4972
csharp
db.HashSet("bike:1", new HashEntry[]
{
new HashEntry("model", "Deimos"),
new HashEntry("brand", "Ergonom"),
new HashEntry("type", "Enduro bikes"),
new HashEntry("price", 4972)
});
Console.WriteLine("Hash Created");
// Hash Created
var model = db.HashGet("bike:1", "model");
Console.WriteLine($"Model: {model}");
// Model: Deimos
var price = db.HashGet("bike:1", "price");
Console.WriteLine($"Price: {price}");
// Price: 4972
var bike = db.HashGetAll("bike:1");
Console.WriteLine("bike:1");
Console.WriteLine(string.Join("\n", bike.Select(b => $"{b.Name}: {b.Value}")));
// Bike:1:
// model: Deimos
// brand: Ergonom
// type: Enduro bikes
// price: 4972
您可以在此文档站点的数据类型部分获取可用数据类型的完整概述。每种数据类型都有允许您操作或检索数据的命令。命令参考 提供了详细的解释。
扫描key空间
Redis 中的每个项目都有一个唯一的键。所有项目都位于 Redis 键空间内。您可以通过 SCAN 命令扫描 Redis key空间。下面是一个扫描前 100 个具有前缀bike:
的键的示例:
bash
SCAN 0 MATCH "bike:*" COUNT 100
SCAN 返回光标位置,允许您迭代扫描下一批键,直到达到光标值 0。
后续步骤
通过了解 Redis Stack,您可以使用 Redis 处理更多使用案例。以下是两个额外的快速入门指南:
- Redis 作为文档数据库
- Redis 作为矢量数据库