node.js 在 redis 中存储对象 [英] node.js store objects in redis

查看:96
本文介绍了node.js 在 redis 中存储对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事情就是这样 - 我想在 redis 中的某个键下存储原生 JS (node.js) 对象(闪存套接字引用).当我使用简单的 client.set() 这样做时,它被存储为一个字符串.当我尝试获取价值时,我得到 [object Object] - 只是一个字符串.

Here is the thing - I want to store native JS (node.js) objects (flash sockets references) in redis under a certain key. When I do that with simple client.set() it's stored as a string. When I try to get value I get [object Object] - just a string.

有机会让这个工作吗?这是我的代码:

Any chance to get this working? Here's my code:

  addSocket : function(sid, socket) {
    client.set(sid, socket);
  },

  getSocket : function(sid) {
    client.get(sid, function(err, reply) {
      // cant't get an object here. All I get is useless string
    });
  },

推荐答案

Downvoters:这里的上下文是 SET 命令和存储任意对象的能力.

不,你不能那样做.您应该接受 Redis 将所有内容存储为字符串的事实(毕竟协议是基于文本的).Redis 可能会执行一些优化并将一些值转换为整数,但这是它的业务,而不是您的业务.

No, you can't do that. You should accept the fact that Redis stores everything as a string (the protocol is text-based, after all). Redis may perform some optimizations and convert some values to integers, but that's its business, not yours.

如果您想在 Redis 中存储任意对象,请确保在保存之前序列化它们并在检索之后反序列化.

If you want to store arbitrary objects in Redis, make sure that you serialize them before saving and de-serialize after retrieving.

不过,我不确定您是否可以使用套接字对象来做到这一点.毕竟,它们只是描述了一个系统资源(一个开放的连接)(例如 TCP 套接字).如果您设法序列化描述并在另一台机器上反序列化它,那台机器将无法连接.

I'm not sure if you can do that with socket objects, though. They simply describe a system resource (an open connection), after all (TCP sockets, for example). If you manage to serialize the description and deserialize it on another machine, that other machine won't have the connection.

这篇关于node.js 在 redis 中存储对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆