如何在 redis 上命名键以避免名称冲突? [英] How to namespace keys on redis to avoid name collisions?

查看:41
本文介绍了如何在 redis 上命名键以避免名称冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 redis 来存储我自己的一些键值对,但是我的一些模块已经在使用它.用于会话数据的 redis express 会话存储,以及用于套接字 io 的 redis 适配器.所以我的问题很简单,如何创建或指定数据库/命名空间来存储我自己的密钥而不会发生密钥冲突?我正在使用 node-redis 驱动程序.

I want to use redis to store some of my own key-value pairs, however some of my modules already use it. The redis express session store for session data, as well as the redis adapter for socket io. So my question is simple, how can I create or designate a database/namespace to store my own keys without key collisions? I am using the node-redis driver.

推荐答案

方案一:不同模块的数据存储在不同的Redis实例中

最严格的隔离是将每个模块的数据存储在一个单独的 Redis 实例中,即一个单独的 Redis 进程中.

The most strictly isolation is storing data of each module in an individual Redis instance, i.e. an individual Redis process.

方案二:将不同模块的数据存储在单个Redis实例的不同数据库中

一个Redis实例可以有多个数据库,你可以在config文件中配置数据库的个数.默认有16个数据库.

A Redis instance can have multiple databases, and you can configure the number of databases in the config file. By default, there are 16 databases.

这些数据库以从零开始的数字索引命名.通过 select 命令,您可以使用 ith<​​/em> 数据库.选择后,任何后续命令都会对ith<​​/em>数据库进行操作.

These databases are named with a zero-based numeric index. With the select command, you can use the ith database. After the selection, any subsequent commands will operate on the ith database.

因此,如果为每个模块分配一个独立的数据库,就可以避免名称冲突.

So, if you assign an independent database for each module, you can avoid name collisions.

注意:此解决方案不适用于 Redis 集群.Redis Cluster 只允许你使用0th 数据库.

NOTE: this solution DOES NOT work with Redis Cluster. Redis Cluster only allows you to use the 0th database.

解决方案 3:使用键前缀创建命名空间

如果您的所有数据都必须存储在单个数据库中,您仍然可以使用 键前缀 隐式创建 命名空间.对于每个模块,该模块的所有数据都应具有相同的键模式:ModuleName:KeyName,即该模块的每个键具有相同的前缀:ModuleName.

If all of your data has to be stored in a single database, you can still implicitly create a namespace with key prefix. For each module, all data of this module should have the same key pattern: ModuleName:KeyName, i.e. each key of this module has the same prefix: ModuleName.

由于每个模块都有不同的名称,因此这些模块之间不会有任何名称冲突:

Since each module has a different name, there won't be any name collisions among these modules:

// Set keys for module1
SET module1:key1 value
SET module1:key2 value

// Set keys for module2
SET module2:key1 value
SET module2:key2 value

注意:此解决方案也适用于 Redis Cluster.

NOTE: this solution also works with Redis Cluster.

这篇关于如何在 redis 上命名键以避免名称冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆