redis lua 库积累

-- lua脚本要求所有的功能,不依赖内部或外部的状态
-- cd /root/workspace/java
-- /usr/local/redis/bin/redis-cli -p 6379 --ldb --eval api.lua r , PRE
-- /usr/local/redis/bin/redis-server 6379.conf
-- /usr/local/redis/bin/redis-cli shutdown

local keys = KEYS
local args = ARGV
local Wtm = {}      -- Wtm library

Wtm.serialize = function(obj)
    local lua = ""
    local t = type(obj)
    if t == "number" then
        lua = lua .. obj
    elseif t == "boolean" then
        lua = lua .. tostring(obj)
    elseif t == "string" then
        lua = lua .. string.format("%q", obj)
    elseif t == "table" then
        lua = lua .. "{\n"
    for k, v in pairs(obj) do
        lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
    end
    local metatable = getmetatable(obj)
        if metatable ~= nil and type(metatable.__index) == "table" then
        for k, v in pairs(metatable.__index) do
            lua = lua .. "[" .. serialize(k) .. "]=" .. serialize(v) .. ",\n"
        end
    end
        lua = lua .. "}"
    elseif t == "nil" then
        return nil
    else
        error("can not serialize a " .. t .. " type.")
    end
    return lua
end

Wtm.log = function ( v )
	redis.log(redis.LOG_WARNING, serialize(v))
end

--usage: redis-cli --eval api.lua k1 , PRE
Wtm.uuid = function (pid)
	-- pid 机器id占4位,左移16位
	local idxNum = redis.call("INCR", "ID_IDX") % 65535

	--获取当前时间戳(秒),左移20位
	local sec = redis.call("TIME")[1]
	return sec*1048576+pid*65536+idxNum
end

Wtm.split = function (str)
	local splitlist = {}  
	string.gsub(str, '[^%s]+', function(w) table.insert(splitlist, w) end ) 
	return splitlist
end

Wtm.callstr = function (str)
	local x = Wtm.split(str)
	local ret = redis.call(unpack(x))
	return ret
end

Wtm.callstrarr = function (arr)
	local retarr = {}
	local fd = ''
	for k,v in pairs(arr) do
		redis.debug(v)
		-- redis.breakpoint()
		fd = string.find(v, "#")
		-- redis.debug(fd)
		if (fd == nil) then
			-- redis.debug('ok run')
			local ret = Wtm.callstr(v)
			table.insert(retarr, ret)
		end
	end
	
	return retarr
end

Wtm.runlstr = function (longstr )
	local splitlist = {}  
	-- 先切分成数组
	string.gsub(longstr, '[^\r\n\t]+', function(w) table.insert(splitlist, w) end ) 
	local ret = Wtm.callstrarr(splitlist)

	return ret
end

Wtm.scanall = function ()
	local retarr = {}
	local ret = ''
	local index = '0'	
	while(true)
	do 
		ret = redis.call('scan',index)
		redis.debug(ret[1])
		redis.debug(ret[1] == '0')
		redis.debug(retarr)
		table.insert(retarr, ret[2])

		if (ret[1] == '0') then break end
		redis.breakpoint()
		index = ret[1]
	end
	-- redis.debug(retarr)
	return retarr
end

Wtm.limit_rate = function(ip)
	local ret = 0  --  正常

	local current = redis.call("incr", ip)
	if tonumber(current) == 1 then
    	redis.call("expire", ip, 10) -- 设置超时时间10s
	end
	
	if tonumber(current) > 10 then
    	ret = 1
	end
	-- redis.debug(redis.call("get", ip))
	return ret
end

local function test_key(prefix)
	-- 种子必须要自己从外部设置,value要随机可以使用redis命令
	-- math.randomseed(tostring(os.time()):reverse():sub(1, 7))
	redis.call('flushall')
	prefix = args[1]
	local ret = {}
	for i=1,10 do
		redis.call('set', prefix .. i, math.random(1,100) +2)
	end

	redis.call('del', prefix .. 2)
	redis.call('expire', prefix .. 3, 30)

	for i=1,10 do
		ret[i] = redis.call('get', prefix .. i)
	end

	redis.debug(ret,1)
	if redis.call('exists', prefix .. 3) then
		redis.debug('ok')
	end

	local status = redis.call('ttl', prefix .. 3)

	-- 排序
	local cmds = {
		'rpush numbers 1 3 5 7 9',
		'rpush numbers 2 4 6 8 10',
		'SORT numbers STORE sorted-numbers',
		'lrange sorted-numbers 0 -1'
	}
	local retu = Wtm.callstrarr(cmds)
	redis.debug(retu)
	
	-- redis.breakpoint()
	redis.call('flushall')
	-- callstr('HMSET user_info_1 name admin level 9999')
	local cmds = {
		'HMSET user_info_1 name admin level 9999',
		'HMSET user_info_2 name jack level 10',
		'HMSET user_info_3 name peter level 25',
		'HMSET user_info_4 name mary level 70',
		'SORT uid BY user_info_*->level',
		'SORT uid BY user_info_*->level GET user_info_*->name',
		'hgetall user_info_1',
		'hgetall user_info_4'
	}

	local retu = Wtm.callstrarr(cmds)
	redis.debug(retu)
	-- redis.breakpoint()

	cmds = [[
		HMSET user_info_1 name admin level 0.01
		HMSET user_info_2 name jack level 0.10
		HMSET user_info_3 name peter level 0.25
		keys user_info_*
		hgetall user_info_4
		 hgetall user_info_1
		 expire user_info_1 1000
		 ttl user_info_1
		 ttl user_info_4
		 ttl user_info_0
		]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	ret = Wtm.scanall()

	return ret
end

local function test_str()
	local ret = ''
	for i=1,100 do
		ret = Wtm.limit_rate('10.88.147.26')
		redis.debug(ret)
	end

	local cmds = [[
		#append拼接字符串
		append serials 0001
		append serials 0002
		append serials 0003
		GETRANGE serials 0 3
		GETRANGE serials 4 7
		GETRANGE serials 8 11
		
		#bit计数
		SETBIT user1 0 1 
		SETBIT user1 4 1
		BITCOUNT user1

		# bit按位操作
		SETBIT bits-1 0 1
		SETBIT bits-1 3 1 
		SETBIT bits-2 0 1
		SETBIT bits-2 1 1
		SETBIT bits-2 3 1
		BITOP AND and-result bits-1 bits-2
		GETBIT and-result 0
		GETBIT and-result 1
		GETBIT and-result 2
		GETBIT and-result 3

		# 递减
		GETSET failure_times 10
		DECR failure_times
		DECRBY failure_times 20
		
		SET greeting hello
		SETRANGE greeting 4 "Redis"
		STRLEN greeting
		MSET date 2012.3.30 time 11:00a.m. weather sunny
		MGET date time weather

		MSETNX rmdbs MySQL nosql MongoDB key-value-store redis
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end

local function test_hash()
	local ret = ''
	local cmds = [[
		HSET website google www.g.cn
		HSET website baidu www.baidu.com
		HSETNX website qq www.qq.com
		HGET website google
		HGETALL website
		HEXISTS website google
		HDEL website google
		HLEN website
		HKEYS website
		HVALS website

		HMSET pet dog doudou cat nounou
		HMGET pet dog cat fake_pet
		HINCRBY counter page_view 200
		HGET counter page_view
		# e是10的指数
		HSET mykey field 5.0e3
		HINCRBYFLOAT mykey field 2.0e-2
		HGET mykey field
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end

local function test_list()
	local ret = ''
	local cmds = [[
		# 左边为前
		# lpush lpop 栈, rpush rpop是队列,  lset linsert lrem 数组
		# index range  读
		# ltrim llen RPOPLPUSH (出队+入栈)
		LPUSH mylist a b c
		LINDEX mylist 0
		LPUSHX mylist hello
		LINSERT mylist BEFORE hello There
		LPOP mylist
		LLEN mylist
		LINDEX mylist 0
		LRANGE mylist 0 -1		
		RPUSH queue a a b c a
		LRANGE queue 0 -1
		LINDEX queue -1
		LREM queue 0 a 
		LRANGE queue 0 -1

		# trim RPOPLPUSH
		LTRIM queue 1 -1
		LRANGE queue 0 -1 
		LPUSH stack 1 2 3 4 5
		RPUSH q1  a b c d e
		RPOPLPUSH q1 stack
		lrange stack 0 -1
		lrange q1 0 -1
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end

local function test_set()
	local ret = ''
	local cmds = [[
		# add rem pop move 
		# card members randmember ismember
		# inter union diff
		
		# 为了保证原子性,交并补的操作需要在前
		SADD A a b c d
		SADD B b c 11 22
		# 第一个参数是操作的结果
		SDIFFSTORE DIFF A B
		SISMEMBER DIFF a
		SISMEMBER DIFF 11

		# 交集
		SINTERSTORE INTER A B 
		SISMEMBER INTER b
		# 并集
		SUNIONSTORE UNION A B 
		SMEMBERS UNION
		
		SMOVE A B a
		SMEMBERS A
		SMEMBERS B
		SADD bbs tianya.cn groups.google.com
		SREM bbs tianya.cn
		SMEMBERS bbs
		SADD tool pc printer phone
		SCARD tool
		SMEMBERS tool
		SPOP tool
		SMEMBERS tool
		SRANDMEMBER tool
		SRANDMEMBER tool
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end
local function test_zset()
	local ret = ''
	local cmds = [[
		# add rem remrangebyrank
		# score相关:(rev)rangebyscore incrby count score
		# card (rev)range (rev)rank
		# interstore unionstores
		
		ZADD page_rank 9 baidu.com  10 google.com 8 bing.com
		ZREM page_rank google.com
		ZCARD page_rank
		zscore page_rank bing.com
		ZRANGE page_rank 0 -1 WITHSCORES
		ZINCRBY page_rank 2 baidu.com
		ZCOUNT page_rank -1 5000 

		ZADD salary 2500 jack 5000 tom 12000 peter
		zrangebyscore salary -inf +inf WITHSCORES
		zrangebyscore salary (2500 +inf WITHSCORES
		zrank salary tom
		zrevrank salary tom
		zrevrange salary 0 -1 WITHSCORES
		# 闭区间
		zremrangebyrank salary 0 1 
		
		# zunionstore
		zadd programmer 2000 peter 3500 jack 5000 tom
		ZRANGE programmer 0 -1 WITHSCORES
		zadd manager 2000 herry 3500 mary 4000 bob
		zrange manager 0 -1 WITHSCORES
		zunionstore salary 2 programmer manager 
		zrange salary 0 -1 withscores

		# zinterstore
		ZADD mid_test 70 LiLei 70 HanMeimei 99.5 Tom 11 one
		ZADD fin_test 88 LiLei 75 HanMeimei 99.5 Tom
		zinterstore sum_point 2 mid_test fin_test
		zrange sum_point 0 -1 withscores
		
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end

local function test_other()
	local ret = ''
	local cmds = [[
		#MONITOR
		# SHUTDOWN
		BGREWRITEAOF
		DBSIZE
		LASTSAVE
		client list
		
		config get *
		CONFIG REWRITE
		CONFIG SET slowlog-log-slower-than 1000
		CONFIG SET slowlog-max-len 1000
		
		info all
		SLOWLOG GET
		SLOWLOG LEN
		SLOWLOG RESET

		SLAVEOF 127.0.0.1 6379	
	]]

	ret = Wtm.runlstr(cmds)
	redis.debug(ret)
	
	redis.breakpoint()
	return ret
end

-- redis.status_reply('status_reply')
-- redis.error_reply('error_reply')

local ret = test_zset()
-- 通过return 自动实现类型转换
return ret

-- ./redis-cli --ldb --eval /tmp/script.lua mykey somekey , arg1 arg2
-- s p l r e

 

猜你喜欢

转载自eric-weitm.iteye.com/blog/2395914