Improve Redis Lua Script Execution Performance

1. Environment

Spring Data Redis 1.4.2

Redis 2.8.x

2. Original Code and Configuration

(1) Script on Spring side

--import dependent files
local priceRedisDao = dofile("script/priceRedisDao.lua")
local eventRedisDao = dofile("script/EventRedisDao.lua")

--one of the functions
local function function1(prices)
	...
  return true
end
Spring application context configuration:

<bean id="priceScript"
	class="org.springframework.data.redis.core.script.DefaultRedisScript">
	<property name="location" value="classpath:processPrice.lua" />
	<property name="resultType" value="java.lang.String" />
</bean>
Java code:
redisTemplate.execute(priceScript, keys);
(2) Note that the dependent scripts were placed on redis installation folder.

3. Analysis

The java code for executing lua script is called very frequently, say 50k times in one second. 

In every call, the lua interpreter would execute the dofile, it means the system compiled and executed the dependent scripts again and again, and again, this must be a performance killer. 

4. Solution

Store(and compile) the lua scripts in Redis once, and look them up and evoke them when needed. How to implement Redis lua stored procedures? following content copied from Reference [1].

# Step 0 -- create test data
redis-cli HSET :object:30343552:data foo bar
 
# Step 1 -- store sample function 'sampleFunction'
redis-cli SET :functions:sample "redis.call('SELECT', 0);local data=redis.call('HGETALL',':object:' .. ARGV[1] .. ':data');return data"
 
# Step 2 -- create function loader
redis-cli SCRIPT LOAD "f=loadstring(redis.call('get',':functions:' .. KEYS[1]));return f()"
 
# Step 3 -- test
redis-cli EVALSHA 7b951bb1cb58cb9de1dee3cb6f79fb089911ff8f 1 sample 30343552
 

Reference:

[1] https://gist.github.com/rbraband/1901178  (Howto implement stored procedures within Redis)

[2] http://stackoverflow.com/questions/22774320/trouble-evoking-lua-stored-procedure-using-evalsha-from-redis

[3] Programming in Lua.

你可能感兴趣的:(Improve Redis Lua Script Execution Performance)