我可以使用 Tarantool 代替 Redis 吗?

Can I use Tarantool instead of Redis?

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

像这样:

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

是的,您可以在 Tarantool 中以比在 Redis 中灵活得多的方式使数据过期。尽管没有 spaces 就无法执行此操作,因为 space 是 Tarantool 中的数据容器(如数据库或其他数据库系统中的 table)。

为了使数据过期,您必须使用 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()