package cache
import "github.com/patrickmn/go-cache"
const (
// 用于需要过期时间的函数
NoExpiration time.Duration = -1
// 用于需要过期时间的函数。 相当于传递与创建缓存时给予New()或NewFrom()相同的到期时间(例如5分钟)。
DefaultExpiration time.Duration = 0
)
type Cache
type Cache struct {
// 包含已过滤或未导出的字段
}
func New
func New(defaultExpiration, cleanupInterval time.Duration) *Cache
返回具有给定默认到期持续时间和清除间隔的新缓存。 如果到期持续时间小于一(或NoExpiration),则缓存中的项永远不会过期(默认情况下),必须手动删除。 如果清理间隔小于1,则在调用c.DeleteExpired()之前,不会从缓存中删除过期的项目。
func NewFrom
func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache
返回具有给定默认到期持续时间和清除间隔的新缓存。如果到期持续时间小于一(或NoExpiration),则缓存中的项永远不会过期(默认情况下),必须手动删除。如果清理间隔小于1,则在调用c.DeleteExpired()之前,不会从缓存中删除过期的项目。
NewFrom()还接受一个项目映射,该映射将用作缓存的底层映射。这对于从反序列化的高速缓存开始(在c.Items()上使用例如gob.Encode()序列化)或者传入例如make(map [string] Item,500)在预期缓存达到某个最小大小时提高启动性能。
只有缓存的方法才能同步对此映射的访问,因此建议不要在创建缓存后保留对映射的任何引用。如果需要,可以使用c.Items()稍后访问地图(同样需要注意)。
关于序列化的注意事项:当使用例如gob,确保gob.Register()在编码使用c.Items()检索的映射之前存储在缓存中的各个类型,并在解码包含项目映射的blob之前注册这些相同的类型。
func (Cache) Add
func (c Cache) Add(k string, x interface{}, d time.Duration) error
仅当给定键的项目尚不存在或者现有项目已过期时,才将项目添加到缓存。 否则返回错误。
func (Cache) Decrement
func (c Cache) Decrement(k string, n int64) error
将int,int8,int16,int32,int64,uintptr,uint,uint8,uint32或uint64,float32或float64类型的项递减n。 如果项的值不是整数,如果未找到,或者如果不能将其递减n,则返回错误。 要检索递减的值,请使用一种专门的方法,例如:DecrementInt64。
func (Cache) DecrementFloat
func (c Cache) DecrementFloat(k string, n float64) error
将float32或float64类型的项递减n。 如果项的值不是浮点数,如果未找到它,或者如果无法将其递减n,则返回错误。 传递一个负数来减少该值。 要检索递减的值,请使用一种专门的方法,例如:DecrementFloat64。
func (Cache) DecrementFloat32
func (c Cache) DecrementFloat32(k string, n float32) (float32, error)
用float减少float32类型的项。 如果项的值不是float32,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementFloat64
func (c Cache) DecrementFloat64(k string, n float64) (float64, error)
用float减少float64类型的项。 如果项的值不是float64,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementInt
func (c Cache) DecrementInt(k string, n int) (int, error)
用n减去int类型的项。 如果项的值不是int,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementInt16
func (c Cache) DecrementInt16(k string, n int16) (int16, error)
将int16类型的项递减n。 如果项的值不是int16,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementInt32
func (c Cache) DecrementInt32(k string, n int32) (int32, error)
用int减少int32类型的项。 如果项的值不是int32,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementInt64
func (c Cache) DecrementInt64(k string, n int64) (int64, error)
用n减去int64类型的项。 如果项的值不是int64,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementInt8
func (c Cache) DecrementInt8(k string, n int8) (int8, error)
用n减去int8类型的项。 如果项的值不是int8,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUint
func (c Cache) DecrementUint(k string, n uint) (uint, error)
用n减去uint类型的项。 如果项目的值不是uint,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUint16
func (c Cache) DecrementUint16(k string, n uint16) (uint16, error)
将类型为uint16的项递减n。 如果项的值不是uint16,或者找不到,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUint32
func (c Cache) DecrementUint32(k string, n uint32) (uint32, error)
用n减去uint32类型的项。 如果项目的值不是uint32,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUint64
func (c Cache) DecrementUint64(k string, n uint64) (uint64, error)
用n减去uint64类型的项。 如果项目的值不是uint64,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUint8
func (c Cache) DecrementUint8(k string, n uint8) (uint8, error)
用n减去uint8类型的项。 如果项目的值不是uint8,或者如果找不到,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) DecrementUintptr
func (c Cache) DecrementUintptr(k string, n uintptr) (uintptr, error)
将类型为uintptr的项递减n。 如果项目的值不是uintptr,或者找不到它,则返回错误。 如果没有错误,则返回递减的值。
func (Cache) Delete
func (c Cache) Delete(k string)
从缓存中删除项目。 如果密钥不在缓存中,则不执行任何操作。
func (Cache) DeleteExpired
func (c Cache) DeleteExpired()
从缓存中删除所有过期的项目。
func (Cache) Flush
func (c Cache) Flush()
从缓存中删除所有项目。
func (Cache) Get
func (c Cache) Get(k string) (interface{}, bool)
从缓存中获取项目。 返回item或nil,以及指示是否找到键的bool。
func (Cache) GetWithExpiration
func (c Cache) GetWithExpiration(k string) (interface{}, time.Time, bool)
GetWithExpiration从缓存中返回一个项目及其到期时间。 它返回项目或nil,如果设置了一个过期时间(如果项目永远不会过期时间为零值,则返回时间),以及指示是否找到密钥的bool。
func (Cache) Increment
func (c Cache) Increment(k string, n int64) error
将int,int8,int16,int32,int64,uintptr,uint,uint8,uint32或uint64,float32或float64类型的项递增n。 如果项的值不是整数,如果未找到,或者无法将其递增n,则返回错误。 要检索递增的值,请使用一种专门的方法,例如:IncrementInt64。
func (Cache) IncrementFloat
func (c Cache) IncrementFloat(k string, n float64) error
Increment an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.
func (Cache) IncrementFloat32
func (c Cache) IncrementFloat32(k string, n float32) (float32, error)
Increment an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementFloat64
func (c Cache) IncrementFloat64(k string, n float64) (float64, error)
Increment an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementInt
func (c Cache) IncrementInt(k string, n int) (int, error)
Increment an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementInt16
func (c Cache) IncrementInt16(k string, n int16) (int16, error)
Increment an item of type int16 by n. Returns an error if the item's value is not an int16, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementInt32
func (c Cache) IncrementInt32(k string, n int32) (int32, error)
Increment an item of type int32 by n. Returns an error if the item's value is not an int32, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementInt64
func (c Cache) IncrementInt64(k string, n int64) (int64, error)
Increment an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementInt8
func (c Cache) IncrementInt8(k string, n int8) (int8, error)
Increment an item of type int8 by n. Returns an error if the item's value is not an int8, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUint
func (c Cache) IncrementUint(k string, n uint) (uint, error)
Increment an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUint16
func (c Cache) IncrementUint16(k string, n uint16) (uint16, error)
Increment an item of type uint16 by n. Returns an error if the item's value is not an uint16, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUint32
func (c Cache) IncrementUint32(k string, n uint32) (uint32, error)
Increment an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUint64
func (c Cache) IncrementUint64(k string, n uint64) (uint64, error)
Increment an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUint8
func (c Cache) IncrementUint8(k string, n uint8) (uint8, error)
Increment an item of type uint8 by n. Returns an error if the item's value is not an uint8, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) IncrementUintptr
func (c Cache) IncrementUintptr(k string, n uintptr) (uintptr, error)
Increment an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the incremented value is returned.
func (Cache) ItemCount
func (c Cache) ItemCount() int
返回缓存中的项目数。 这可能包括已过期但尚未清理的项目。
func (Cache) Items
func (c Cache) Items() map[string]Item
将缓存中的所有未过期项目复制到新映射中并将其返回。
func (Cache) Load
func (c Cache) Load(r io.Reader) error
从io.Reader添加(Gob序列化)缓存项,排除当前缓存中已存在(并且尚未过期)密钥的任何项。
注意:不推荐使用此方法,而使用c.Items()和NewFrom()(请参阅NewFrom()的文档。)
func (Cache) LoadFile
func (c Cache) LoadFile(fname string) error
从给定文件名加载和添加缓存项,不包括当前缓存中已存在的键的任何项。
注意:不推荐使用此方法,而使用c.Items()和NewFrom()(请参阅NewFrom()的文档。)
func (Cache) OnEvicted
func (c Cache) OnEvicted(f func(string, interface{}))
设置一个(可选)函数,当从缓存中逐出项目时,使用键和值调用该函数。 (包括手动删除时,但不会被覆盖。)设置为nil以禁用。
func (Cache) Replace
func (c Cache) Replace(k string, x interface{}, d time.Duration) error
仅当缓存键已存在并且现有项尚未过期时,才为其设置新值。 否则返回错误。
func (Cache) Save
func (c Cache) Save(w io.Writer) (err error)
将缓存的项目(使用Gob)写入io.Writer。
注意:不推荐使用此方法,而使用c.Items()和NewFrom()(请参阅NewFrom()的文档。)
func (Cache) SaveFile
func (c Cache) SaveFile(fname string) error
将缓存的项目保存到给定的文件名,如果文件不存在则创建该文件,如果存在则覆盖它。
注意:不推荐使用此方法,而使用c.Items()和NewFrom()(请参阅NewFrom()的文档。)
func (Cache) Set
func (c Cache) Set(k string, x interface{}, d time.Duration)
将项添加到缓存,替换任何现有项。 如果持续时间为0(DefaultExpiration),则使用缓存的默认到期时间。 如果为-1(NoExpiration),则该项永不过期。
func (Cache) SetDefault
func (c Cache) SetDefault(k string, x interface{})
使用默认过期将项添加到缓存中,替换任何现有项。
type Item
type Item struct {
Object interface{}
Expiration int64
}
func (Item) Expired
func (item Item) Expired() bool
如果项目已过期,则返回true。
package bson
import "labix.org/v2/mgo/bson"
包bson是Go的BSON规范的实现:
http://bsonspec.org
它是作为Go的mgo MongoDB驱动程序的一部分创建的,但它是独立的,可以在没有驱动程序的情况下单独使用。
var MaxKey = orderKey(1<<63 - 1)
MaxKey是一个特殊值,它比MongoDB数据库中的所有其他可能的BSON值更高。
var MinKey = orderKey(-1 << 63)
MinKey是一个特殊值,它比MongoDB数据库中的所有其他可能的BSON值低。
var SetZero = errors.New("set to zero")
可以从SetBSON方法返回SetZero,以将值设置为其各自的零值。 在指针值中使用时,这会将字段设置为nil而不是预先分配的值。
var Undefined undefined
未定义表示未定义的BSON值。
func IsObjectIdHex
func IsObjectIdHex(s string) bool
IsObjectIdHex返回s是否是ObjectId的有效十六进制表示。 请参见ObjectIdHex函数。
func Marshal
func Marshal(in interface{}) (out []byte, err error)
Marshal序列化in值,可以是map或struct值。 对于struct值,仅序列化导出的字段。 小写字段名称用作每个导出字段的键,但可以使用相应的字段标记更改此行为。 标签还可以包含用于调整字段的编组行为的标志。 接受的标记格式为:
"[<key>][,<flag1>[,<flag2>]]"
`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
目前支持以下标志:
omitempty 如果字段未设置为零,则仅包括该字段 类型或空切片或映射的值。
minsize 如果可行的话,将int64值编组为int32,同时保留数值。
inline 内联字段,必须是结构或映射, 导致其所有字段或键被处理,如同 他们是外部结构的一部分。 对于映射,键必须 不与其他struct字段的bson键冲 突。
Some examples:
type T struct {
A bool
B int "myb"
C string "myc,omitempty"
D string `bson:",omitempty" json:"jsonkey"`
E int64 ",minsize"
F int64 "myf,omitempty,minsize"
}
func Now
func Now() time.Time
现在以毫秒精度返回当前时间。 MongoDB以相同的精度存储时间戳,因此从该方法返回的Time在往返数据库后不会改变。 这是此功能存在的唯一原因。 使用time.Now函数也可以正常工作。
func Unmarshal
func Unmarshal(in []byte, out interface{}) (err error)
Unmarshal将数据从in反序列化为out值。 out值必须是map,指向struct的指针或指向bson.D值的指针。 小写字段名称用作每个导出字段的键,但可以使用相应的字段标记更改此行为。 标签还可以包含用于调整字段的编组行为的标志。 接受的标记格式为:
"[<key>][,<flag1>[,<flag2>]]"
`(...) bson:"[<key>][,<flag1>[,<flag2>]]" (...)`
在unmarshal期间当前支持以下标志(有关其他标志,请参阅Marshal方法):
inline 内联该字段,该字段必须是结构或map。内联结构体的处理就像它的字段是外部结构的一部分一样。 内联映射导致与任何其他结构字段不匹配的键被插入到映射中,而不是像往常一样被丢弃。
out的目标字段或元素类型可能不一定与所提供数据的BSON值匹配。 以下转换是自动进行的:
- 如果正确保留值的整数部分,则转换数字类型
- Bool转换为数字类型为1或0 - 如果不是0,则将数值类型转换为bools为true或否则为 - 否则将二进制和字符串BSON数据转换为字符串,数组或字节切片
如果该值不适合该类型且无法转换,则会以静默方式跳过该值。
必要时初始化指针值。
type Binary
type Binary struct {
Kind byte
Data []byte
}
二进制是非标准二进制值的表示。 任何一种都应该有效,但在撰写本文时已知如下:
0x00 - Generic. This is decoded as []byte(data), not Binary{0x00, data}.
0x01 - Function (!?)
0x02 - Obsolete generic.
0x03 - UUID
0x05 - MD5
0x80 - User defined.
type D
type D []DocElem
D表示包含有序元素的BSON文档。 例如:
bson.D{{"a", 1}, {"b", true}}
在某些情况下,例如在为MongoDB创建索引时,定义元素的顺序很重要。 如果顺序不重要,使用map通常会更舒适。 见bson.M和bson.RawD。
func (D) Map
func (d D) Map() (m M)
Map从d中返回有序元素名称/值对中的映射。
type DocElem
type DocElem struct {
Name string
Value interface{}
}
See the D type.
type Getter
type Getter interface {
GetBSON() (interface{}, error)
}
实现bson.Getter接口的值将在必须编组给定值时调用其GetBSON方法,并且将对此方法的结果进行封送以代替实际对象。
如果GetBSON返回返回非零错误,则编组过程将停止并使用提供的值进行错误输出。
type JavaScript
type JavaScript struct {
Code string
Scope interface{}
}
JavaScript是一种包含JavaScript代码的类型。 如果Scope为非零,则它将被编组为从标识符到可在评估提供的代码时使用的值的映射。
type M
type M map[string]interface{}
M是map [string] interface {}映射的方便别名,对于以本机方式处理BSON非常有用。 例如:
bson.M{"a": 1, "b": true}
除了对等效map类型所做的事情外,对此类型没有特殊处理。 map中的元素将以未定义的顺序转储。 另请参阅有序替代的bson.D类型。
type MongoTimestamp
type MongoTimestamp int64
MongoTimestamp是MongoDB使用的一种特殊内部类型,由于某些奇怪的原因,它在BSON中定义了自己的数据类型。
type ObjectId
type ObjectId string
ObjectId是标识BSON值的唯一ID。 它必须正好是12个字节长。 默认情况下,MongoDB对象在其“_id”属性中设置了这样的属性。
http://www.mongodb.org/display/DOCS/Object+IDs
func NewObjectId
func NewObjectId() ObjectId
NewObjectId返回一个新的唯一ObjectId。
func NewObjectIdWithTime
func NewObjectIdWithTime(t time.Time) ObjectId
NewObjectIdWithTime返回一个虚拟ObjectId,其时间戳部分填充了从纪元UTC开始提供的秒数,以及所有其他填充零的部分。 插入具有此方法生成的id的文档是不安全的,它仅对查询查找在指定时间戳之前或之后生成的ID的文档非常有用。
func ObjectIdHex
func ObjectIdHex(s string) ObjectId
ObjectIdHex从提供的十六进制表示返回ObjectId。 使用无效的十六进制表示调用此函数将导致运行时出现紧急情况。 请参阅IsObjectIdHex函数。
func (ObjectId) Counter
func (id ObjectId) Counter() int32
Counter返回id的递增值部分。 使用无效的id调用此方法是一个运行时错误。
func (ObjectId) Hex
func (id ObjectId) Hex() string
十六进制返回ObjectId的十六进制表示。
func (ObjectId) Machine
func (id ObjectId) Machine() []byte
Machine返回id的3字节机器id部分。 使用无效的id调用此方法是一个运行时错误。
func (ObjectId) MarshalJSON
func (id ObjectId) MarshalJSON() ([]byte, error)
MarshalJSON将bson.ObjectId转换为json.Marshaller。
func (ObjectId) Pid
func (id ObjectId) Pid() uint16
Pid返回id的进程id部分。 使用无效的id调用此方法是一个运行时错误。
func (ObjectId) String
func (id ObjectId) String() string
String返回id的十六进制字符串表示形式。 示例:ObjectIdHex(“4d88e15b60f486e428412dc9”)。
func (ObjectId) Time
func (id ObjectId) Time() time.Time
Time返回id的时间戳部分。 使用无效的id调用此方法是一个运行时错误。
func (*ObjectId) UnmarshalJSON
func (id *ObjectId) UnmarshalJSON(data []byte) error
UnmarshalJSON turns *bson.ObjectId into a json.Unmarshaller.
func (ObjectId) Valid
func (id ObjectId) Valid() bool
如果id有效,则返回true。 有效的id必须包含12个字节。
type Raw
type Raw struct {
Kind byte
Data []byte
}
Raw类型表示原始未处理的BSON文档和元素。 Kind是根据BSON规范定义的元素种类,Data是各个元素的原始未处理数据。 使用此类型可以部分地解组或编组值。
相关文件:
http://bsonspec.org/#/specification
func (Raw) Unmarshal
func (raw Raw) Unmarshal(out interface{}) (err error)
Unmarshal将raw反序列化为out值。 如果out值类型与raw不兼容,则返回* bson.TypeError。
有关解组过程的更多详细信息,请参阅Unmarshal函数文档。
type RawD
type RawD []RawDocElem
RawD表示包含原始未处理元素的BSON文档。 当懒惰地处理不确定内容的文档时,或者当操纵原始内容文档时,这种低级表示可能是有用的。
type RawDocElem
type RawDocElem struct {
Name string
Value Raw
}
See the RawD type.
type RegEx
type RegEx struct {
Pattern string
Options string
}
RegEx表示正则表达式。 “选项”字段可能包含定义应用模式的方式的单个字符,并且必须进行排序。 撰写本文时的有效选项是“i”表示不区分大小写匹配,“m”表示多行匹配,“x”表示详细模式,“l”表示\ w,\ W,类似的是与语言环境相关的, s'为全点模式('''匹配所有内容),'u'使\ w,\ W和类似的匹配unicode。 在编组成BSON格式之前,不验证Options参数的值。
type Setter
type Setter interface {
SetBSON(raw Raw) error
}
实现bson.Setter接口的值将在解组期间通过SetBSON方法接收BSON值,并且对象本身不会像往常一样更改。
如果设置值有效,则该方法应返回nil或者bson.SetZero,以将相应字段设置为零值(指针类型为nil)。 如果SetBSON返回类型为bson.TypeError的值,则将从正在解码的映射或切片中省略BSON值,并且将继续解组。 如果它返回任何其他非零错误,则解组过程将停止并使用提供的值进行错误输出。
该接口通常在指针接收器中有用,因为该方法将需要改变接收器。 但是,实现Setter接口的类型字段不必是指针。
与通常的行为不同,对实现Setter接口的值进行解组不会将值重置为零状态。 这允许值自行决定如何解组。
For example:
type MyString string
func (s *MyString) SetBSON(raw bson.Raw) error {
return raw.Unmarshal(s)
}
type Symbol
type Symbol string
符号类型类似于字符串,用于具有不同符号类型的语言。
type TypeError
type TypeError struct {
Type reflect.Type
Kind byte
}
func (*TypeError) Error
func (e *TypeError) Error() string
package redis
import "github.com/garyburd/redigo/redis"
Package redis是Redis数据库的客户端。
Redigo常见问题解答(https://github.com/garyburd/redigo/wiki/FAQ)包含有关此软件包的更多文档。
Conn接口是与Redis一起使用的主要接口。 应用程序通过调用Dial,DialWithTimeout或NewConn函数来创建连接。 将来,将添加功能以创建分片和其他类型的连接。
应用程序完成连接后,应用程序必须调用连接Close方法。
Conn接口具有执行Redis命令的通用方法:
Do(commandName string, args ...interface{}) (reply interface{}, err error)
Redis命令参考(http://redis.io/commands)列出了可用的命令。 使用Redis APPEND命令的示例是:
n, err := conn.Do("APPEND", "key", "value")
Do方法将命令参数转换为批量字符串,以便传输到服务器,如下所示:
Go Type Conversion
[]byte Sent as is
string Sent as is
int, int64 strconv.FormatInt(v)
float64 strconv.FormatFloat(v, 'g', -1, 64)
bool true -> "1", false -> "0"
nil ""
all other types fmt.Fprint(w, v)
Redis命令回复类型使用以下Go类型表示:
Redis type Go type
error redis.Error
integer int64
simple string string
bulk string []byte or nil if value not present.
array []interface{} or nil if value not present.
使用类型断言或回复助手函数将接口{}转换为命令结果的特定Go类型。
Connections使用Send,Flush和Receive方法支持管道传输。
Send(commandName string, args ...interface{}) error
Flush() error
Receive() (reply interface{}, err error)
发送将命令写入连接的输出缓冲区。 刷新将连接的输出缓冲区刷新到服务器。 接收从服务器读取单个回复。 以下示例显示了一个简单的管道。
c.Send("SET", "foo", "bar")
c.Send("GET", "foo")
c.Flush()
c.Receive() // reply from SET
v, err = c.Receive() // reply from GET
Do方法结合了Send,Flush和Receive方法的功能。 Do方法首先写入命令并刷新输出缓冲区。 接下来,Do方法接收所有待处理的回复,包括刚刚发送的命令的回复。 如果收到的任何回复都是错误,则Do返回错误。 如果没有错误,则Do返回最后一个回复。 如果Do方法的命令参数为“”,则Do方法将刷新输出缓冲区并接收挂起的回复而不发送命令。
使用Send和Do方法实现流水线事务。
c.Send("MULTI")
c.Send("INCR", "foo")
c.Send("INCR", "bar")
r, err := c.Do("EXEC")
fmt.Println(r) // prints [1, 1]
Connections支持Receive方法的一个并发调用者和Send和Flush方法的一个并发调用者。 不支持其他并发,包括对Do方法的并发调用。
要完全并发访问Redis,请使用线程安全池从goroutine中获取,使用和释放连接。 从池返回的连接具有上一段中描述的并发限制。
使用Send,Flush和Receive方法实现Pub / Sub订阅者。
c.Send("SUBSCRIBE", "example")
c.Flush()
for {
reply, err := c.Receive()
if err != nil {
return err
}
// process pushed message
}
PubSubConn类型使用便利方法包装Conn以实现订阅者。 Subscribe,PSubscribe,Unsubscribe和PUnsubscribe方法发送和刷新订阅管理命令。 receive方法将推送的消息转换为方便的类型,以便在类型开关中使用。
psc := redis.PubSubConn{Conn: c}
psc.Subscribe("example")
for {
switch v := psc.Receive().(type) {
case redis.Message:
fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
case redis.Subscription:
fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
case error:
return v
}
}
Bool,Int,Bytes,String,Strings和Values函数将回复转换为特定类型的值。 为了方便地包含对连接Do和Receive方法的调用,这些函数采用了类型为error的第二个参数。 如果错误是非nil,则辅助函数返回错误。 如果错误为nil,则该函数将回复转换为指定的类型:
exists, err := redis.Bool(c.Do("EXISTS", "foo"))
if err != nil {
// handle error return from c.Do or type conversion error.
}
Scan函数将数组回复的元素转换为Go类型:
var value1 int
var value2 string
reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
if err != nil {
// handle error
}
if _, err := redis.Scan(reply, &value1, &value2); err != nil {
// handle error
}
连接方法从服务器返回错误回复类型为redis.Error。
调用连接Err()方法以确定连接是否遇到不可恢复的错误,例如网络错误或协议解析错误。 如果Err()返回非零值,则连接不可用,应该关闭。
此示例使用WATCH / MULTI / EXEC和脚本编写实现了在http://redis.io/topics/transactions中描述的ZPOP。
Code:
package main
import (
"fmt"
"github.com/garyburd/redigo/redis"
)
// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands.
func zpop(c redis.Conn, key string) (result string, err error) {
defer func() {
// Return connection to normal state on error.
if err != nil {
c.Do("DISCARD")
}
}()
// Loop until transaction is successful.
for {
if _, err := c.Do("WATCH", key); err != nil {
return "", err
}
members, err := redis.Strings(c.Do("ZRANGE", key, 0, 0))
if err != nil {
return "", err
}
if len(members) != 1 {
return "", redis.ErrNil
}
c.Send("MULTI")
c.Send("ZREM", key, members[0])
queued, err := c.Do("EXEC")
if err != nil {
return "", err
}
if queued != nil {
result = members[0]
break
}
}
return result, nil
}
// zpopScript pops a value from a ZSET.
var zpopScript = redis.NewScript(1, `
local r = redis.call('ZRANGE', KEYS[1], 0, 0)
if r ~= nil then
r = r[1]
redis.call('ZREM', KEYS[1], r)
end
return r
`)
// This example implements ZPOP as described at
// http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting.
func main() {
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
// Add test data using a pipeline.
for i, member := range []string{"red", "blue", "green"} {
c.Send("ZADD", "zset", i, member)
}
if _, err := c.Do(""); err != nil {
fmt.Println(err)
return
}
// Pop using WATCH/MULTI/EXEC
v, err := zpop(c, "zset")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
// Pop using a script.
v, err = redis.String(zpopScript.Do(c, "zset"))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(v)
}
var ErrNil = errors.New("redigo: nil returned")
ErrNil表示回复值为零。
var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
当达到池中的最大数据库连接数时,将从池连接方法(Do,Send,Receive,Flush,Err)返回ErrPoolExhausted。
func Bool
func Bool(reply interface{}, err error) (bool, error)
Bool是一个将命令回复转换为布尔值的助手。 如果err不等于nil,则Bool返回false,错误。 否则Bool将回复转换为boolean,如下所示:
Reply type Result
integer value != 0, nil
bulk string strconv.ParseBool(reply)
nil false, ErrNil
other false, error
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Do("SET", "foo", 1)
exists, _ := redis.Bool(c.Do("EXISTS", "foo"))
fmt.Printf("%#v\n", exists)
Output:
true
func ByteSlices
func ByteSlices(reply interface{}, err error) ([][]byte, error)
ByteSlices是一个帮助器,它将数组命令的回复转换为[] []字节。 如果err不等于nil,则ByteSlices返回nil,错误。 零数组项目保持无效。 如果数组项不是批量字符串或nil,则ByteSlices返回错误。
func Bytes
func Bytes(reply interface{}, err error) ([]byte, error)
字节是一个帮助器,它将命令答复转换为一个字节片。 如果err不等于nil,则Bytes返回nil,错误。 否则,Bytes将回复转换为一个字节切片,如下所示:
Reply type Result
bulk string reply, nil
simple string []byte(reply), nil
nil nil, ErrNil
other nil, error
func DoWithTimeout
func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error)
DoWithTimeout使用指定的读取超时执行Redis命令。 如果连接不满足ConnWithTimeout接口,则返回错误。
func Float64
func Float64(reply interface{}, err error) (float64, error)
Float64是一个帮助程序,它将命令回复转换为64位浮点数。 如果err不等于nil,则Float64返回0,错误。 否则,Float64将回复转换为int,如下所示:
Reply type Result
bulk string parsed reply, nil
nil 0, ErrNil
other 0, error
func Float64s
func Float64s(reply interface{}, err error) ([]float64, error)
Float64s是一个帮助器,它将数组命令的回复转换为[] float64。 如果err不等于nil,则Float64s返回nil,错误。 Nil数组项在输出切片中转换为0。 如果数组项不是批量字符串或nil,则Floats64返回错误。
func Int
func Int(reply interface{}, err error) (int, error)
Int是一个将命令回复转换为整数的帮助器。 如果err不等于nil,那么Int返回0,错误。 否则,Int将回复转换为int,如下所示:
Reply type Result
integer int(reply), nil
bulk string parsed reply, nil
nil 0, ErrNil
other 0, error
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Do("SET", "k1", 1)
n, _ := redis.Int(c.Do("GET", "k1"))
fmt.Printf("%#v\n", n)
n, _ = redis.Int(c.Do("INCR", "k1"))
fmt.Printf("%#v\n", n)
Output:
1
2
func Int64
func Int64(reply interface{}, err error) (int64, error)
Int64是一个帮助程序,它将命令回复转换为64位整数。 如果err不等于nil,那么Int返回0,错误。 否则,Int64将回复转换为int64,如下所示:
Reply type Result
integer reply, nil
bulk string parsed reply, nil
nil 0, ErrNil
other 0, error
func Int64Map
func Int64Map(result interface{}, err error) (map[string]int64, error)
Int64Map是一个帮助器,它将字符串数组(交替键,值)转换为map [string] int64。 HGETALL命令以此格式返回回复。 结果中需要偶数个值。
func Int64s
func Int64s(reply interface{}, err error) ([]int64, error)
Int64s是一个帮助器,它将数组命令的回复转换为[] int64。 如果err不等于nil,则Int64s返回nil,错误。 零数组项目保持无效。 如果数组项不是批量字符串或nil,Int64s将返回错误。
func IntMap
func IntMap(result interface{}, err error) (map[string]int, error)
IntMap是一个帮助器,它将字符串数组(交替键,值)转换为map [string] int。 HGETALL命令以此格式返回回复。 结果中需要偶数个值。
func Ints
func Ints(reply interface{}, err error) ([]int, error)
Ints是一个帮助器,它将数组命令的回复转换为[] in。 如果err不等于nil,则Ints返回nil,错误。 零数组项目保持无效。 如果数组项不是批量字符串或nil,则Ints返回错误。
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Do("SADD", "set_with_integers", 4, 5, 6)
ints, _ := redis.Ints(c.Do("SMEMBERS", "set_with_integers"))
fmt.Printf("%#v\n", ints)
Output:
[]int{4, 5, 6}
func MultiBulk
func MultiBulk(reply interface{}, err error) ([]interface{}, error)
MultiBulk是一个帮助器,它将数组命令回复转换为[]接口{}。
不推荐使用:改为使用值。
func Positions
func Positions(result interface{}, err error) ([]*[2]float64, error)
Positions是一个帮助器,它将位置数组(lat,long)转换为[] [2] float64。 GEOPOS命令以此格式返回回复。
func ReceiveWithTimeout
func ReceiveWithTimeout(c Conn, timeout time.Duration) (interface{}, error)
ReceiveWithTimeout接收具有指定读取超时的回复。 如果连接不满足ConnWithTimeout接口,则返回错误。
func Scan
func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error)
从src扫描副本到dest指向的值。
如果可用,扫描使用RedisScan:
dest指向的值必须是整数,浮点数,布尔值,字符串,[]字节,接口{}或这些类型的切片。 Scan使用标准的strconv包将批量字符串转换为数字和布尔类型。
如果dest值为nil,则跳过相应的src值。
如果src元素为nil,则不修改相应的dest值。
为了能够在循环中轻松使用Scan,Scan会根据复制的值返回src片。
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
c.Send("HMSET", "album:3", "title", "Beat")
c.Send("LPUSH", "albums", "1")
c.Send("LPUSH", "albums", "2")
c.Send("LPUSH", "albums", "3")
values, err := redis.Values(c.Do("SORT", "albums",
"BY", "album:*->rating",
"GET", "album:*->title",
"GET", "album:*->rating"))
if err != nil {
fmt.Println(err)
return
}
for len(values) > 0 {
var title string
rating := -1 // initialize to illegal value to detect nil.
values, err = redis.Scan(values, &title, &rating)
if err != nil {
fmt.Println(err)
return
}
if rating == -1 {
fmt.Println(title, "not-rated")
} else {
fmt.Println(title, rating)
}
}
Output:
Beat not-rated
Earthbound 1
Red 5
func ScanSlice
func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
ScanSlice将src扫描到dest指向的切片。 dest切片的元素必须是整数,浮点数,布尔值,字符串,结构或指向struct值的指针。
结构字段必须是整数,浮点数,布尔值或字符串值。 除非使用fieldNames指定子集,否则将使用所有结构字段。
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
c.Send("HMSET", "album:3", "title", "Beat", "rating", 4)
c.Send("LPUSH", "albums", "1")
c.Send("LPUSH", "albums", "2")
c.Send("LPUSH", "albums", "3")
values, err := redis.Values(c.Do("SORT", "albums",
"BY", "album:*->rating",
"GET", "album:*->title",
"GET", "album:*->rating"))
if err != nil {
fmt.Println(err)
return
}
var albums []struct {
Title string
Rating int
}
if err := redis.ScanSlice(values, &albums); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%v\n", albums)
Output:
[{Earthbound 1} {Beat 4} {Red 5}]
func ScanStruct
func ScanStruct(src []interface{}, dest interface{}) error
ScanStruct将src中的名称和值交替扫描到结构中。 HGETALL和CONFIG GET命令以此格式返回回复。
ScanStruct使用导出的字段名称来匹配响应中的值。 使用'redis'字段标记覆盖名称:
Field int `redis:"myName"`
标签为redis的字段:“ - ”将被忽略。
如果可用,每个字段都使用RedisScan:支持Integer,float,boolean,string和[] byte字段。 Scan使用标准strconv包将批量字符串值转换为数字和布尔类型。
如果src元素为nil,则不修改相应的字段。
func String
func String(reply interface{}, err error) (string, error)
String是一个将命令回复转换为字符串的帮助器。 如果err不等于nil,则String返回“”,错误。 否则String将回复转换为字符串,如下所示:
Reply type Result
bulk string string(reply), nil
simple string reply, nil
nil "", ErrNil
other "", error
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
c.Do("SET", "hello", "world")
s, err := redis.String(c.Do("GET", "hello"))
fmt.Printf("%#v\n", s)
Output:
"world"
func StringMap
func StringMap(result interface{}, err error) (map[string]string, error)
StringMap是一个帮助器,它将字符串数组(交替键,值)转换为map [string]字符串。 HGETALL和CONFIG GET命令以此格式返回回复。 结果中需要偶数个值。
func Strings
func Strings(reply interface{}, err error) ([]string, error)
字符串是一个帮助器,它将数组命令的回复转换为[]字符串。 如果err不等于nil,那么Strings返回nil,错误。 Nil数组项在输出切片中转换为“”。 如果数组项不是批量字符串或nil,则字符串返回错误。
func Uint64
func Uint64(reply interface{}, err error) (uint64, error)
Uint64是一个帮助程序,它将命令回复转换为64位整数。 如果err不等于nil,那么Int返回0,错误。 否则,Int64将回复转换为int64,如下所示:
Reply type Result
integer reply, nil
bulk string parsed reply, nil
nil 0, ErrNil
other 0, error
func Values
func Values(reply interface{}, err error) ([]interface{}, error)
值是将数组命令回复转换为[]接口{}的帮助程序。 如果err不等于nil,那么Values返回nil,错误。 否则,值将转换如下:
Reply type Result
array reply, nil
nil nil, ErrNil
other nil, error
type Args
type Args []interface{}
Args是从结构化值构造命令参数的帮助器。
Code:
c, err := dial()
if err != nil {
fmt.Println(err)
return
}
defer c.Close()
var p1, p2 struct {
Title string `redis:"title"`
Author string `redis:"author"`
Body string `redis:"body"`
}
p1.Title = "Example"
p1.Author = "Gary"
p1.Body = "Hello"
if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
fmt.Println(err)
return
}
m := map[string]string{
"title": "Example2",
"author": "Steve",
"body": "Map",
}
if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
fmt.Println(err)
return
}
for _, id := range []string{"id1", "id2"} {
v, err := redis.Values(c.Do("HGETALL", id))
if err != nil {
fmt.Println(err)
return
}
if err := redis.ScanStruct(v, &p2); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v\n", p2)
}
Output:
{Title:Example Author:Gary Body:Hello}
{Title:Example2 Author:Steve Body:Map}
func (Args) Add
func (args Args) Add(value ...interface{}) Args
添加返回将值附加到args的结果。
func (Args) AddFlat
func (args Args) AddFlat(v interface{}) Args
AddFlat返回将展平值v附加到args的结果。
通过将交替键和映射值附加到args来平面化地图。
通过将切片元素附加到args来切片。
通过将导出的字段的交替名称和值附加到args来展平结构。 如果v是nil结构指针,则不会附加任何内容。 'redis'字段标记覆盖struct字段名称。 有关使用'redis'字段标记的更多信息,请参阅ScanStruct。
其他类型按原样附加到args。
type Argument
type Argument interface {
// RedisArg returns a value to be encoded as a bulk string per the
// conversions listed in the section 'Executing Commands'.
// Implementations should typically return a []byte or string.
RedisArg() interface{}
}
参数是一个对象实现的接口,该对象想要控制对象如何转换为Redis批量字符串。
type Conn
type Conn interface {
// Close closes the connection.
Close() error
// Err returns a non-nil value when the connection is not usable.
Err() error
// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
// Send writes the command to the client's output buffer.
Send(commandName string, args ...interface{}) error
// Flush flushes the output buffer to the Redis server.
Flush() error
// Receive receives a single reply from the Redis server
Receive() (reply interface{}, err error)
}
Conn表示与Redis服务器的连接。
func Dial
func Dial(network, address string, options ...DialOption) (Conn, error)
拨号使用指定的选项连接到给定网络和地址的Redis服务器。
Connect to local instance of Redis running on the default port.
Code:
c, err := redis.Dial("tcp", ":6379")
if err != nil {
// handle error
}
defer c.Close()
func DialTimeout
func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)
DialTimeout就像Dial一样,但需要超时来建立与服务器的连接,编写命令和阅读回复。
不推荐使用:改为使用拨号选项。
func DialURL
func DialURL(rawurl string, options ...DialOption) (Conn, error)
DialURL使用Redis URI方案连接到给定URL的Redis服务器。 网址应遵循该计划的IANA规范草案(https://www.iana.org/assignments/uri-schemes/prov/redis)。
Connect to remote instance of Redis using a URL.
Code:
c, err := redis.DialURL(os.Getenv("REDIS_URL"))
if err != nil {
// handle connection error
}
defer c.Close()
func NewConn
func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn
NewConn为给定的网络连接返回新的Redigo连接。
func NewLoggingConn
func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
NewLoggingConn返回连接周围的日志包装器。
type ConnWithTimeout
type ConnWithTimeout interface {
Conn
// Do sends a command to the server and returns the received reply.
// The timeout overrides the read timeout set when dialing the
// connection.
DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error)
// Receive receives a single reply from the Redis server. The timeout
// overrides the read timeout set when dialing the connection.
ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error)
}
ConnWithTimeout是一个可选接口,允许调用者覆盖连接的默认读取超时。 此接口对于执行BLPOP,BRPOP,BRPOPLPUSH,XREAD以及在服务器上阻塞的其他命令非常有用。
使用DialReadTimeout拨号选项设置连接的默认读取超时。 应用程序应该依赖于不在服务器上阻塞的命令的默认超时。
此包中的所有Conn实现都满足ConnWithTimeout接口。
使用DoWithTimeout和ReceiveWithTimeout辅助函数来简化此接口的使用。
type DialOption
type DialOption struct {
// contains filtered or unexported fields
}
DialOption指定用于拨打Redis服务器的选项。
func DialConnectTimeout
func DialConnectTimeout(d time.Duration) DialOption
DialConnectTimeout指定在未指定DialNetDial选项时连接到Redis服务器的超时。
func DialDatabase
func DialDatabase(db int) DialOption
DialDatabase指定拨打连接时要选择的数据库。
func DialKeepAlive
func DialKeepAlive(d time.Duration) DialOption
DialKeepAlive指定在未指定DialNetDial选项时与Redis服务器的TCP连接的保持活动期。 如果为零,则不启用keep-alives。 如果未指定DialKeepAlive选项,则使用默认值5分钟来确保检测到半封闭的TCP会话。
func DialNetDial
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption
DialNetDial指定用于创建TCP连接的自定义拨号功能,否则使用通过其他选项自定义的net.Dialer。 DialNetDial会覆盖DialConnectTimeout和DialKeepAlive。
func DialPassword
func DialPassword(password string) DialOption
DialPassword指定连接到Redis服务器时使用的密码。