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

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

问题描述

我想使用 redis 来存储我自己的一些键值对,但是我的一些模块已经使用了它.会话数据的 redis express 会话存储,以及 socket 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实例可以有多个数据库,你可以在配置文件中配置数据库的数量.默认情况下,有 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 Cluster.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天全站免登陆