Storing nested javascript objects in redis - NodeJS

前端 未结 1 1876
南笙
南笙 2021-01-05 07:58

I recently switched from memcached to redis in nodejs. The thing I liked in node-memcached was that I can save the whole javascript object in the memory. Sadly I couldn\'t d

相关标签:
1条回答
  • 2021-01-05 08:46

    First of all redis only supports the following data types:

    1. String
    2. List
    3. Set
    4. Hash
    5. Sorted set

    You'll need to store objects as string in both redis and memcached.

    node-memcached parses/stringifies the data automatically. But node-redis doesn't.

    However, you can implement your own serialization/deserialization functions for your app.

    The way node-memcached stringifies an object is as follows:

    if (Buffer.isBuffer(value)) {
        flag = FLAG_BINARY;
        value = value.toString('binary');
    } else if (valuetype === 'number') {
        flag = FLAG_NUMERIC;
        value = value.toString();
    } else if (valuetype !== 'string') {
        flag = FLAG_JSON;
        value = JSON.stringify(value);
    }
    

    It also parses the retrieved text this way:

    switch (flag) {
        case FLAG_JSON:
            dataSet = JSON.parse(dataSet);
            break;
        case FLAG_NUMERIC:
            dataSet = +dataSet;
            break;
        case FLAG_BINARY:
            tmp = new Buffer(dataSet.length);
            tmp.write(dataSet, 0, 'binary');
            dataSet = tmp;
            break;
    }
    
    0 讨论(0)
提交回复
热议问题