Solution 1: Store data of different modules in different Redis instances
The most strictly isolation is storing data of each module in an individual Redis instance, i.e. an individual Redis process.
Solution 2: Store data of different modules in different databases of a single Redis instance
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.
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.
NOTE: this solution DOES NOT work with Redis Cluster
. Redis Cluster
only allows you to use the 0th database.
Solution 3: Create namespace with key prefix
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
NOTE: this solution also works with Redis Cluster
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…