【问题标题】:Can I use Tarantool instead of Redis?我可以使用 Tarantool 代替 Redis 吗?
【发布时间】:2018-12-01 22:59:22
【问题描述】:

我想使用 Tarantool 来存储数据。如何使用 TTL 和简单逻辑(不带空格)存储数据?

像这样:

box:setx(key, value, ttl);
box:get(key)

【问题讨论】:

    标签: tarantool


    【解决方案1】:

    是的,您可以在 Tarantool 中以比在 Redis 中更灵活的方式使数据过期。虽然没有空格你不能这样做,因为空间是 Tarantool 中数据的容器(就像其他数据库系统中的数据库或表)。

    为了使数据过期,您必须使用tarantoolctl rocks install expirationd 命令安装expirationd tarantool rock。关于expirationd 守护进程的完整文档可以在here 找到。

    请随意使用下面的示例代码:

    #!/usr/bin/env tarantool
    
    package.path = './.rocks/share/tarantool/?.lua;' .. package.path
    
    local fiber = require('fiber')
    local expirationd = require('expirationd')
    
    
    -- setup the database
    
    box.cfg{}
    box.once('init', function()
        box.schema.create_space('test')
        box.space.test:create_index('primary', {parts = {1, 'unsigned'}})
    end)
    
    -- print all fields of all tuples in a given space
    local print_all = function(space_id)
        for _, v in ipairs(box.space[space_id]:select()) do
            local s = ''
            for i = 1, #v do s = s .. tostring(v[i]) .. '\t' end
            print(s)
        end
    end
    
    -- return true if tuple is more than 10 seconds old
    local is_expired = function(args, tuple)
        return (fiber.time() - tuple[3]) > 10
    end
    
    -- simply delete a tuple from a space
    local delete_tuple = function(space_id, args, tuple)
        box.space[space_id]:delete{tuple[1]}
    end
    
    local space = box.space.test
    
    print('Inserting tuples...')
    
    space:upsert({1, '0 seconds', fiber.time()}, {})
    fiber.sleep(5)
    space:upsert({2, '5 seconds', fiber.time()}, {})
    fiber.sleep(5)
    space:upsert({3, '10 seconds', fiber.time()}, {})
    
    print('Tuples are ready:\n')
    
    print_all('test')
    
    print('\nStarting expiration daemon...\n')
    
    -- start expiration daemon
    -- in a production full_scan_time should be bigger than 1 sec
    expirationd.start('expire_old_tuples', space.id, is_expired, {
        process_expired_tuple = delete_tuple, args = nil,
        tuples_per_iteration = 50, full_scan_time = 1
    })
    
    fiber.sleep(5)
    print('\n\n5 seconds passed...')
    print_all('test')
    
    fiber.sleep(5)
    print('\n\n10 seconds passed...')
    print_all('test')
    
    fiber.sleep(5)
    print('\n\n15 seconds passed...')
    print_all('test')
    
    os.exit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-11
      • 2022-01-23
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多