如何在Windows中运行redis lua脚本

时间:2016-04-18 16:32:59

标签: windows lua redis

我遇到了关于如何针对redis运行lua脚本的this文章。但是这篇文章面向那些在* nix上运行的人。如何从Windows环境中执行redis lua脚本?

1 个答案:

答案 0 :(得分:1)

先阅读:

执行此操作并与此脚本作战近一周后,我决定尝试使用其中一个java库来编写脚本。我已经在其中创建了一个包含该项目的公共回购。好处是你不仅限于一个~8000字符的输入变量,它的运行速度要快得多。我将把批处理脚本留给那些绝对需要这样做的人,但我强烈建议使用java代码:

Redis Scripting Project

实际答案:

使用批处理文件,我能够从该文章中复制bash脚本。

@echo off
setlocal EnableDelayedExpansion

echo Starting removal of keys from redis. 
echo KeyMatch: %1 
echo Field: %2
echo Script: %3
echo Host: %4
echo Port: %5

REM set the cursor to 0 to begin iterating over matching keys
set cursor=0

:loop
REM call redis scan and output the result to temp.txt
call redis-cli -h %4 -p %5 scan !cursor! match %1 count 180 > temp.txt

REM set the first line of the temp file to the new cursor variable
set /p cursor=<temp.txt

REM outer loop variables
set /A i=0
set keyString=

REM loop through the text file to build the key string
for /F "usebackq delims=" %%a in ("temp.txt") do (
    set /A i+=1
    REM if we are not on the first line save the key to a space delimted string
    if NOT !i! == 1 (
        call set keyString=!keyString! %%a
    )
)

rem if there is only one line in the file skip the script execution
if !i! LEQ 1 (
    goto :checkCursor
)

rem check that the length of keyString will not likely violate the 8192 character limit to command line calls
ECHO !keyString!> strlength.txt
FOR %%? IN (strlength.txt) DO ( SET /A strlength=%%~z? - 2 )
if !strlength! GTR 8000 (
    echo.
    echo.
    echo ****Error processing script. Key string is too long. Reduce the count in call to scan.****
    echo.
    echo.
    GOTO :end
)

REM call the script with the keys from the scan task, output to result.txt to prevent writing to the command line each iteration.   
call redis-cli -h %4 -p %5 --eval %3 !keyString:~1! , %2 > result.txt

REM output '.' to the commandline to signify progress
<nul set /p=.

:checkCursor
if not !cursor!==0 (
    goto :loop
)

:end
set fileToDelete=temp.txt
if exist !fileToDelete! del /F !fileToDelete!
set fileToDelete=result.txt
if exist !fileToDelete! del /F !fileToDelete!
set fileToDelete=strlength.txt
if exist !fileToDelete! del /F !fileToDelete!

echo Completed script execution
endlocal

您可以从命令行调用此脚本,如:

batchScriptName keyMatch field luaScriptName.lua host port
batchScriptName myKey* us luaScriptName.lua localhost 6379

如果批处理脚本不在您的路径上,则必须从文件所在的目录中调用该命令。另外,使用lua脚本,您需要提供完整的文件路径引用,或者从lua脚本所在的目录中调用批处理脚本。

此脚本设置为使用redis中的散列值。如果你需要改变它,你可能想要改变这一行:

call redis-cli -h %4 -p %5 --eval %3 !keyString:~1! , %2 > result.txt

'%2'将字段值传递给lua脚本中的ARGV数组,如果不需要,可以删除它。您还可以根据需要添加其他ARGV参数。