本文整理汇总了Golang中github.com/garyburd/redigo/redis.NewScript函数的典型用法代码示例。如果您正苦于以下问题:Golang NewScript函数的具体用法?Golang NewScript怎么用?Golang NewScript使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewScript函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: StartKV
func StartKV(db *DB, pool *redis.Pool) {
kvDB = db
redisPool = pool
c := redisPool.Get()
defer c.Close()
//cmdSetKV: key, value, expireTime
cmdSetKV = redis.NewScript(3, SCRIPT_SET_KV)
err := cmdSetKV.Load(c)
PanicIfError(err)
//cmdGetDel: key, value, expireTime
cmdGetDel = redis.NewScript(1, SCRIPT_GETDEL)
err = cmdGetDel.Load(c)
PanicIfError(err)
//cmdGetExpiredKV: key, value, expireTime
cmdGetExpiredKV = redis.NewScript(1, SCRIPT_GET_EXPIRED_KV)
err = cmdGetExpiredKV.Load(c)
PanicIfError(err)
//start save to db task
go RepeatSingletonTask(redisPool, "kvSaveToDbTask", saveToDBTask)
//go RepeatSingletonTask(redisPool, "hkvSaveToDB", hkvSaveToDB)
}
示例2: NewMutex
// Each lock will have a name which corresponds to a key in the Redis server.
// The mutex will also be initialized with a uuid. The mutex uuid
// can be used to extend the TTL for the lock.
func NewMutex(name string, ttl time.Duration) *Mutex {
m := new(Mutex)
m.Name = name
m.Ttl = ttl
m.Backoff = time.Second
m.id = uuid()
m.lock = redis.NewScript(1, luaLock)
m.unlock = redis.NewScript(1, luaUnlock)
return m
}
示例3: init
func init() {
genericScript = strings.NewReplacer(
"INSERTSUFFIX", insertSuffix,
"DELETESUFFIX", deleteSuffix,
).Replace(genericScript)
insertScript = redis.NewScript(1, strings.NewReplacer(
"REMSUFFIX", deleteSuffix, // Insert script does ZREM from deletes key
"ADDSUFFIX", insertSuffix, // and ZADD to inserts key
).Replace(genericScript))
deleteScript = redis.NewScript(1, strings.NewReplacer(
"REMSUFFIX", insertSuffix, // Delete script does ZREM from inserts key
"ADDSUFFIX", deleteSuffix, // and ZADD to deletes key
).Replace(genericScript))
}
示例4: ReadAllTasks
// ReadAllTasks load all unfinished task
func ReadAllTasks() []Task {
c := Pool.Get()
defer c.Close()
var GetAllTasksLua = `
local data = redis.call("LRANGE", "allTasks", "0", "-1")
local ret = {}
for idx=1, #data do
ret[idx] = redis.call("HGETALL", "task:"..data[idx])
end
return ret
`
var tasks []Task
script := redis.NewScript(0, GetAllTasksLua)
values, err := redis.Values(script.Do(c))
if err != nil {
log.Println(err)
}
for i := range values {
t := new(Task)
redis.ScanStruct(values[i].([]interface{}), t)
tasks = append(tasks, *t)
}
return tasks
}
示例5: Init
func (rli *RedisInput) Init(config interface{}) error {
rli.conf = config.(*RedisInputConfig)
var err error
rli.conn, err = redis.Dial("tcp", rli.conf.Address)
if err != nil {
return fmt.Errorf("connecting to - %s", err.Error())
}
if _, err = rli.conn.Do("AUTH", rli.conf.Password); err != nil {
rli.conn.Close()
return fmt.Errorf("AUTH - %s", err.Error())
}
rli.batchlpop = redis.NewScript(1, `
local i = tonumber(ARGV[1])
local res = {}
local length = redis.call('llen',KEYS[1])
if length < i then i = length end
while (i > 0) do
local item = redis.call("lpop", KEYS[1])
if (not item) then
break
end
table.insert(res, item)
i = i-1
end
return res
`)
return nil
}
示例6: getFreePort
func getFreePort(c *redis.Conn) int {
// refreshOccupiedPorts(c)
s := redis.NewScript(3, `
redis.call("SDIFFSTORE", KEYS[3], KEYS[1], KEYS[2])
redis.call("ZINTERSTORE", KEYS[3], 1, KEYS[3])
local freePort = redis.call("ZRANGE", KEYS[3], 0, 0)[1]
redis.call("SADD", KEYS[2], freePort)
if freePort == nil then
return 0
else
return freePort
end
`)
r, e := redis.Int(s.Do(*c,
getKey("ports", "possible"),
getKey("ports", "occupied"),
getKey("ports", "available")))
if e != nil {
log.Panic("Unable to fetch a free port: ", e)
}
return r
}
示例7: setTags
func setTags(prefix string, metrics string, tags []string) string {
//TODO: call function
client := clientFunction()
defer client.Close()
hashName := prefix + metrics + "\tTagHash"
listName := prefix + metrics + "\tTagList"
args := []string{}
args = append(args, tags...)
args = append(args, hashName)
args = append(args, listName)
scriptArgs := make([]interface{}, len(args))
for i, v := range args {
scriptArgs[i] = v
}
s := getLuaScript("setTag")
script := redis.NewScript(len(tags), s)
result, err := redis.String(script.Do(client, scriptArgs...))
if err != nil {
log.Println(err)
}
return result
}
示例8: Set
func (this __red__model_ServiceType__field_SomeInt) Set(value int) {
conn := this.__.(redis.Conn)
{
value := __red__to_string(value)
_, err := redis.NewScript(0, `
local rut = {}
do
local sort = function (arr) table.sort(arr, function (a, b) return a[1] < b[1] end); return arr end
rut.pack = function (v) return cmsgpack.pack(sort(v)) end
rut.hash = function (v) return redis.sha1hex(rut.pack(v)) end
end
local prim = ARGV[1]
local value = ARGV[2]
local baseKey = "red::obj::ServiceType::base::" .. prim
local set = function ()
redis.call("hset", baseKey, "SomeInt", value)
end
do
--> Unique index
local _SomeInt = redis.call("hget", baseKey, "SomeInt") or ""
local oldKey = "red::idx::ServiceType::SomeInt::" .. rut.hash({
{"SomeInt", _SomeInt},
})
local newKey = "red::idx::ServiceType::SomeInt::" .. rut.hash({
{"SomeInt", value },
})
-- TODO: Ensure uniqueness
-- TODO: What to do if key exists?
if redis.call("exists", oldKey) then
redis.call("set", newKey, prim)
set()
redis.call("del", oldKey)
else
redis.call("set", newKey, prim)
set()
end
end
`).Do(conn, this.__model.__prim, value, __red__to_string(time.Now().UTC().Unix()))
if err != nil {
panic(err)
}
}
}
示例9: InitRedix
func InitRedix(addr string) {
Redix = make([]redis.Conn, _Max)
RedixMu = make([]*sync.Mutex, _Max)
var err error
for i := 0; i < _Max; i++ {
Redix[i], err = redis.Dial("tcp", addr)
if err != nil {
panic(err)
}
RedixMu[i] = &sync.Mutex{}
glog.Infof("RedisPool[%d] Init OK on %s\n", i, addr)
}
RedixAddr = addr
netAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
panic(err)
}
RedixAddrPool = []net.Addr{netAddr}
ScriptSelectMobileId = redis.NewScript(1, _scriptSelectMobileId)
ScriptSelectMobileId.Load(Redix[_SelectMobileId])
ScriptOnline = redis.NewScript(2, _scriptOnline)
ScriptOnline.Load(Redix[_SetUserOnline])
ScriptOffline = redis.NewScript(2, _scriptOffline)
ScriptOffline.Load(Redix[_SetUserOffline])
if gCometType != msgs.CometUdp || gCometUdpSubBindingEvent {
err = SubDeviceUsers()
if err != nil {
panic(err)
}
}
err = SubModifiedPasswd()
if err != nil {
panic(err)
}
if gCometType != msgs.CometUdp || gCometPushUdp {
err = SubCommonMsg()
if err != nil {
panic(err)
}
}
}
示例10: ExampleScript
func ExampleScript(c redis.Conn, reply interface{}, err error) {
// Initialize a package-level variable with a script.
var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`)
// In a function, use the script Do method to evaluate the script. The Do
// method optimistically uses the EVALSHA command. If the script is not
// loaded, then the Do method falls back to the EVAL command.
reply, err = getScript.Do(c, "foo")
}
示例11: TestScript
func TestScript(t *testing.T) {
c, err := redistest.Dial()
if err != nil {
t.Fatalf("error connection to database, %v", err)
}
defer c.Close()
// To test fall back in Do, we make script unique by adding comment with current time.
script := fmt.Sprintf("--%d\nreturn {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}", time.Now().UnixNano())
s := redis.NewScript(2, script)
reply := []interface{}{[]byte("key1"), []byte("key2"), []byte("arg1"), []byte("arg2")}
v, err := s.Do(c, "key1", "key2", "arg1", "arg2")
if err != nil {
t.Errorf("s.Do(c, ...) returned %v", err)
}
if !reflect.DeepEqual(v, reply) {
t.Errorf("s.Do(c, ..); = %v, want %v", v, reply)
}
err = s.Load(c)
if err != nil {
t.Errorf("s.Load(c) returned %v", err)
}
err = s.SendHash(c, "key1", "key2", "arg1", "arg2")
if err != nil {
t.Errorf("s.SendHash(c, ...) returned %v", err)
}
err = c.Flush()
if err != nil {
t.Errorf("c.Flush() returned %v", err)
}
v, err = c.Receive()
if !reflect.DeepEqual(v, reply) {
t.Errorf("s.SendHash(c, ..); c.Receive() = %v, want %v", v, reply)
}
err = s.Send(c, "key1", "key2", "arg1", "arg2")
if err != nil {
t.Errorf("s.Send(c, ...) returned %v", err)
}
err = c.Flush()
if err != nil {
t.Errorf("c.Flush() returned %v", err)
}
v, err = c.Receive()
if !reflect.DeepEqual(v, reply) {
t.Errorf("s.Send(c, ..); c.Receive() = %v, want %v", v, reply)
}
}
示例12: LPOPRPUSH
func LPOPRPUSH(cnx redis.Conn) *redis.Script {
lmu.Lock()
defer lmu.Unlock()
if lpoprpush == nil {
lpoprpush = redis.NewScript(2, lpoprpushSrc)
}
return lpoprpush
}
示例13: NewProvider
func (c RedisProviderConfig) NewProvider() (Provider, error) {
p := &RedisProvider{
BaseProvider: BaseProvider{c},
}
p.pool = redis.Pool{
MaxIdle: 10,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
conn, err := redis.Dial("tcp", c.Host+":"+strconv.Itoa(c.Port))
if err != nil {
return nil, err
}
if len(c.Password) > 0 {
if _, err := conn.Do("AUTH", c.Password); err != nil {
conn.Close()
return nil, err
}
}
if _, err := conn.Do("SELECT", c.Database); err != nil {
conn.Close()
return nil, err
}
return conn, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
p.countScript = redis.NewScript(0, `return #redis.call('keys', '::till:value:*')`)
p.randomValueKeyScript = redis.NewScript(0, `
local keys = redis.call('keys', '::till:value:*')
if #keys > 0 then
return keys[1]
else
return nil
end
`)
return p, nil
}
示例14: CreateMemo
// CreateMemo saves a memo
func CreateMemo(user, when, memo string) {
c := Pool.Get()
defer c.Close()
var setMemoLua = `
local id = redis.call("INCR", "memoIncrId")
redis.call("RPUSH", KEYS[1]..":memos", id)
redis.call("HMSET", "memo:"..id, "time", KEYS[2], "content", KEYS[3])
`
script := redis.NewScript(3, setMemoLua)
script.Do(c, user, when, memo)
}
示例15: DeleteMemo
// DeleteMemo deletes a memo
func DeleteMemo(user string, index int) {
c := Pool.Get()
defer c.Close()
var deleteMemoLua = `
local id = redis.call("LINDEX", KEYS[1]..":memos", KEYS[2])
redis.call("LREM", KEYS[1]..":memos", 1, id)
redis.call("DEL", "memo:"..id)
`
script := redis.NewScript(2, deleteMemoLua)
script.Do(c, user, index)
}