How to store array of objects in Redis?

后端 未结 3 1233
时光取名叫无心
时光取名叫无心 2021-01-13 06:44

I have an array of Objects that I want to store in Redis. I can break up the array part and store them as objects but I am not getting how I can get somethings like

<
3条回答
  •  梦毁少年i
    2021-01-13 06:52

    The thing I found working was storing the key as a unique identifier and stringifying the whole object while storing the data and applying JSON.parse while extracting it.

    Example code:

    client
        .setAsync(obj.deviceId.toString(), JSON.stringify(obj))
        .then((doc) => {
            return client.getAsync(obj.deviceId.toString());
        })
        .then((doc) => {
            return JSON.parse(doc);
        }).catch((err) => {
            return err;
        });
    

    Though stringifying and then parsing it back is a computationally heavy operation and will block the Node.js server if the size of JSON becomes large. I am probably ready to take a hit for lesser complexity because I know my JSON wouldn't be huge, but that needs to be kept in mind while going for this approach.

提交回复
热议问题