如何在windows中运行redis lua脚本

我看到了这篇文章,讲述了如何对redis运行lua脚本。但这篇文章面向的是在*nix上运行的用户。在windows环境中,如何执行redis lua脚本呢?

点赞
用户1547153
用户1547153

阅读须知:

在与本脚本苦战了一周之后,我决定尝试使用其中一个 Java 库来执行脚本。我创建了一个包含该项目的公共存储库。好处是您没有限制于 ~8000 个字符的输入变量,而且运行速度快得多。我将在此保留批处理脚本,供那些绝对需要这样做的人使用,但我强烈建议改用 Java 代码:

Redis 脚本项目

实际答案:

使用批处理文件,我能够复制该篇文章中的 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

如果您的批处理脚本不在 PATH 中,则必须从文件所在的目录调用该命令。而对于 Lua 脚本,您需要提供完整的文件路径引用或从 Lua 脚本所在的目录调用批处理脚本。

该脚本配置为与 Redis 的哈希值一起工作。如果需要更改,请更改以下行:

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

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

2016-04-18 16:32:58