|
| 1 | +Scripting |
| 2 | +=== |
| 3 | + |
| 4 | +Basic [Lua scripting](http://redis.io/commands/EVAL) is supported by the `IServer.ScriptLoad(Async)`, `IServer.ScriptExists(Async)`, `IServer.ScriptExists(Async)`, `IDatabase.ScriptEvaluate`, and `IDatabaseAsync.ScriptEvaluateAsync` methods. |
| 5 | +These methods expose the basic commands neccessary to submit and execute Lua scripts to redis. |
| 6 | + |
| 7 | +More sophisticated scripting is available through the `LuaScript` class. The `LuaScript` class makes it simpler to prepare and submit parameters along with a script, as well as allowing you to use |
| 8 | +cleaner variables names. |
| 9 | + |
| 10 | +An example use of the `LuaScript`: |
| 11 | + |
| 12 | +``` |
| 13 | + const string Script = "redis.call('set', @key, @value)"; |
| 14 | +
|
| 15 | + using (ConnectionMultiplexer conn = /* init code */) |
| 16 | + { |
| 17 | + var db = conn.GetDatabase(0); |
| 18 | +
|
| 19 | + var prepared = LuaScript.Prepare(Script); |
| 20 | + db.ScriptEvaluate(prepared, new { key = (RedisKey)"mykey", value = 123 }); |
| 21 | + } |
| 22 | +``` |
| 23 | + |
| 24 | +The `LuaScript` class rewrites variables in scripts of the form `@myVar` into the appropriate `ARGV[someIndex]` required by redis. If the |
| 25 | +parameter passed is of type `RedisKey` it will be sent as part of the `KEYS` collection automatically. |
| 26 | + |
| 27 | +Any object that exposes field or property members with the same name as @-prefixed variables in the Lua script can be used as a paramter hash to |
| 28 | +`Evaluate` calls. Supported member types are the following: |
| 29 | + |
| 30 | + - int(?) |
| 31 | + - long(?) |
| 32 | + - double(?) |
| 33 | + - string |
| 34 | + - byte[] |
| 35 | + - bool(?) |
| 36 | + - RedisKey |
| 37 | + - RedisValue |
| 38 | + |
| 39 | + |
| 40 | +To avoid retransmitting the Lua script to redis each time it is evaluated, `LuaScript` objects can be converted into `LoadedLuaScript`s via `LuaScript.Load(IServer)`. |
| 41 | +`LoadedLuaScripts` are evaluated with the [`EVALSHA`](http://redis.io/commands/evalsha), and referred to by hash. |
| 42 | + |
| 43 | +An example use of `LoadedLuaScript`: |
| 44 | + |
| 45 | +``` |
| 46 | + const string Script = "redis.call('set', @key, @value)"; |
| 47 | +
|
| 48 | + using (ConnectionMultiplexer conn = /* init code */) |
| 49 | + { |
| 50 | + var db = conn.GetDatabase(0); |
| 51 | + var server = conn.GetServer(/* appropriate parameters*/); |
| 52 | +
|
| 53 | + var prepared = LuaScript.Prepare(Script); |
| 54 | + var loaded = prepared.Load(server); |
| 55 | + loaded.Evaluate(db, new { key = (RedisKey)"mykey", value = 123 }); |
| 56 | + } |
| 57 | +``` |
| 58 | + |
| 59 | +All methods on both `LuaScript` and `LoadedLuaScript` have Async alternatives, and expose the actual script submitted to redis as the `ExecutableScript` property. |
0 commit comments