0

我正在尝试将大型数据库查询结果存储在 memcached 服务器中以便更快地检索,并在使用brotli进入 memcache 之前压缩数据。

我一直在尝试使用这样的示例对象进行测试:

//cacheserver already defined and connected
let brotli_config = {
    mode: 1, //0=regular, 1=text
    quality: 8 //1=fast .. 11=small
}

let test_key = 'paths_100'
let test_value = [
    {
        text: 'this is text',
        outlines: 'this is an outline',
        inlines: 'this is an inline'
    }
]

let compressed_in = require('brotli/compress')(JSON.stringify(test_value), brotli_config)
console.log(compressed_in) //LOG 1
cacheserver.set(test_key, compressed_in, {
        expires: 3600
    },
    function(err) {
        cacheserver.get(test_key, function(err, compressed_out) {
            console.log(compressed_out) //LOG 2

            let string_out = require('brotli/decompress')(compressed_out)
            console.log(string_out) //LOG 3
        })
    }
)

这是输出:

//LOG 1
Uint8Array(10) [
  27, 86,   0,  0, 36,
   0,  2, 177, 64, 32
]

//LOG 2
<Buffer 1b 56 00 00 24 00 02 b1 40 20>

//LOG 3
Uint8Array(87) [
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0
]

我正在将对象转换为字符串(对于性能来说可能不是一个好主意,但是使用 brotli 模式 0 并且不进行字符串化不起作用;返回 null ...),压缩它,将 10 条目 uint8array 存储在缓存中服务器,检索一个 10 字节的缓冲区,并解压缩它。但是,解压缩的结果只是一个零数组。这里发生了什么事?我是第一次使用这个压缩库和 memcached 客户端 ( memjs ),所以任何关于如何正确使用它们的信息都非常感谢。

4

1 回答 1

1

我想出了一个解决方案(让我知道它是否可以加快速度)。非常感谢这篇博文阐明了 nodejs 对象、字符串和缓冲区之间的关系。

在将对象数据传递给 brotli 之前,我错过了从字符串到缓冲区的转换。完整的过程现在看起来像这样:

let data = {/* stuff */}
let test_key = 'paths_100'
let compressed_in = require('brotli/compress')(Buffer.from(JSON.stringify(test_value),'utf-8'), brotli_config)
cacheserver.set(test_key, compressed_in, {
        expires: 3600
    },
    function(err) {
        cacheserver.get(test_key, function(err, compressed_out) {
            let data_out = JSON.parse(Buffer.from(require('brotli/decompress')(compressed_out)).toString('utf-8'))
        })
    }
)
于 2020-05-24T17:42:48.823 回答