1

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

像这样:

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

1 回答 1

5

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

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

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

#!/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()
于 2017-12-06T14:08:14.760 回答