【问题标题】:LUA script for modification object in RedisRedis中修改对象的LUA脚本
【发布时间】:2021-06-27 06:10:00
【问题描述】:

我需要一个关于在 Redis 中修改对象的 LUA 脚本的简短建议。 我有这样的实体的 Redis 列表:

{
  "@class": "com.myproject.model.Book",
  "bookId": "someId",
  "author": "someAuthor"
}

现在,我需要更改我的实体以允许某本书有多个作者,并为此创建迁移脚本:

{
  "@class": "com.myproject.model.Book",
  "bookId": "someId",
  "authors":  [
           "java.util.ArrayList",
            [
              "someAuthor"
            ]
         ]
}

我认为我需要用 LUA 做什么:

local book
local cacheName --cache name in my case
local authorId;

local size = redis.call('LLEN', cacheName)
if size == 0
then
    return -1
end

while size > 0
do
    book = redis.call('LPOP', cacheName)
    
    -- modify entity here 

    affectedEntitiesCount = affectedEntitiesCount + 1
    redis.call('RPUSH', cacheName, book)
    size = size - 1
end
return affectedEntitiesCount

但我不知道如何根据要求修改书。 有人可以看看并建议吗?

【问题讨论】:

    标签: redis lua


    【解决方案1】:

    已解决:

    local book
    local cacheName
    local authorPattern= '"author":"[^"]*"'
    local authorId
    local replacementAuthors = '"authors":["java.util.ArrayList",["%s"]]'
    
    local size = redis.call('LLEN', cacheName)
    if size == 0
    then
        return -1
    end
    
    while size > 0
    do
        book = redis.call('LPOP', cacheName)
        
        authorId = string.match(string.match(book, authorPattern), [["authorId":"([^"]+)]])
        replacedAuthors = string.format(replacedAuthors , authorId)
        book = string.gsub(book, authorPattern, replacedAuthors)
        
        affectedEntitiesCount = affectedEntitiesCount + 1
        redis.call('RPUSH', cacheName, book)
        size = size - 1
    end
    return affectedEntitiesCount
    

    【讨论】:

      【解决方案2】:

      由于您似乎在列表中存储 JSON 编码的值,您可以使用嵌入在 Redis 的 Lua 引擎中的 cjson library

      例如:

          ...
          book = cjson.decode(redis.call('LPOP', cacheName))
          book['bookId'] = book['bookId']..'foo' -- concat 'foo' to bookId
          ...
          redis.call('RPUSH', cacheName, cjson.encode(book))
      

      注意:还要确保使用KEYS 输入数组来参数化脚本的输入键名称(例如local cacheName = KEYS[1]

      【讨论】:

        猜你喜欢
        • 2017-11-25
        • 2014-10-08
        • 2018-08-05
        • 1970-01-01
        • 1970-01-01
        • 2015-10-27
        • 2021-04-15
        • 2020-11-08
        • 2015-06-18
        相关资源
        最近更新 更多