I want to store a hash/JSON data of users in Redis and want to add the user in users hash the user data like this.
For example, users = {}
;
When user rahul logs in then users
will become.
users = {
rahul: {
username: 'rahul',
}
}
And when user namita login then
users = {
rahul: {
username: 'rahul',
},
namita: {
username: 'namita',
}
}
What will the code be to do this in Redis?
How will I initialise the key users
and add rahul to it?
Out of this set, hset, etc., which function do I need to use?
And how will I retrieve the data of users['rahul']
via Redis?
Create new session. js file in the root directory with the following content: const express = require('express'); const session = require('express-session'); const redis = require('redis'); const client = redis. createClient(); const redisStore = require('connect-redis')(session); const app = express(); app.
In the above example, hash data type is used to store the user's object which contains basic information of the user. Here HMSET, HGETALL are commands for Redis, while user − 1 is the key. Every hash can store up to 232 - 1 field-value pairs (more than 4 billion).
const express = require('express'); const fetch = require('node-fetch'); const NodeCache = require('node-cache'); // stdTTL is the default time-to-live for each cache entry const myCache = new NodeCache({ stdTTL: 600 }); // retrieve some data from an API async function getPosts() { const response = await fetch(`https ...
With Redis Enterprise, you can use Redis as both an in-memory cache and a primary database in a single system, thus eliminating the complexity and latency of two separate systems.
Probably the most optimal solution to store single hash/json would be to use hashes commands. I also had this "dilemma" and there are several questions regarding data structure containing users with JSON-like objects in Redis.
EDIT
Use node_redis module. It's actively maintained by a pro a probably the most used node.js driver for Redis. First you should use SADD command to add your new JSON object name into the set in order to track which items "users" contain. Then use HMSET to store "user:rahul" object key-value hashes. Example:
// add first user
client.sadd("users", "user:rahul");
client.hmset("user:rahul", "username", "rahul", "foo", "bar");
// add second user
client.sadd("users", "user:namita");
client.hmset("user:namita", "username", "namita", "foo", "baz");
You can now access your users by various types of redis hash command depending if you want to retrieve only certain hash values or the entire single user object. To get all of the users you can use SMEMBERS command for example. Try to look at the node_redis readme and examples where you should find more information about its API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With