在Go语言中将一个对象存储在GAE的memcache中

huangapple go评论76阅读模式
英文:

Store an object in memcache of GAE in Go

问题

我想使用Go将一个对象存储在GAE的内存缓存中。GAE文档只展示了如何存储[]byte类型的对象,链接在这里:https://developers.google.com/appengine/docs/go/memcache/overview

当然,有一般的方法可以将对象序列化为[]byte,通过这种方式可以完成我的任务。但是通过阅读内存缓存参考文档,我发现在memcache Item中有一个"Object":

// Object是Item的值,用于与编解码器一起使用。
Object interface{}

这似乎是一个内置的机制,用于在内存缓存中存储对象。然而,GAE文档没有提供示例代码。

请问有人可以给我一个示例吗?提前感谢。

英文:

I want to store an object in GAE's memcache using Go. The gae documentation only shows how to store a []byte here: https://developers.google.com/appengine/docs/go/memcache/overview

Of course there are general ways to serialize an object into []byte, by which my task could be accomplished. But by reading the memcache reference, I found there is an "Object" in the memcache Item:

// Object is the Item's value for use with a Codec.
Object interface{}

That seems to be a built-in mechanic to store an object in memcache. However, the gae documentation did not provide a sample code.

Could anyone please show me an example? Thanks in advance

答案1

得分: 27

好的,我刚刚自己弄清楚了。memcache包有两个内置的编解码器:gob和json。只需使用其中一个(当然也可以创建自己的编解码器):

var in, out struct {I int;}

// 将in放入memcache
in.I = 100 
item := &memcache.Item {
   Key: "TestKey",
   Object: in, 
}   
memcache.Gob.Set(c, item)  // 省略了错误检查以方便演示

// 检索值
memcache.Gob.Get(c, "TestKey", &out)
fmt.Fprint(w, out)  // 将打印{100}

谢谢大家。

英文:

OK, I just figured it out my self. The memcache pkg has two built-in Codec: gob and json. Just use one of them (or of course one can create his own Codec):

var in, out struct {I int;}

// Put in into memcache
in.I = 100 
item := &memcache.Item {
   Key: "TestKey",
   Object: in, 
}   
memcache.Gob.Set(c, item)  // error checking omitted for convenience

// retrieve the value
memcache.Gob.Get(c, "TestKey", &out)
fmt.Fprint(w, out)  // will print {100}

Thanks all

huangapple
  • 本文由 发表于 2012年11月7日 14:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/13264555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定