MemoryStoreQueue
*Este conteúdo é traduzido por IA (Beta) e pode conter erros. Para ver a página em inglês, clique aqui.
Fornece acesso a uma fila dentro do MemoryStore.Uma fila é uma estrutura de dados que fornece armazenamento temporário para itens arbitrários (até o limite máximo de tamanho de item -- veja Limites do armazenamento de memória).Cada item da fila tem uma prioridade numérica: o Armazenamento de Memória recupera itens com prioridade maior da fila primeiro e recupera itens com a mesma prioridade em ordem de adição.
Itens na fila podem opcionalmente ser definidos para expirar após um determinado período de tempo.Itens expirados simplesmente desaparecem da fila como se nunca tivessem sido adicionados.
Resumo
Métodos
Adiciona um item à fila.
Lê um ou mais itens da fila.
Remove um item ou itens previamente lidos da fila.
Propriedades
Métodos
AddAsync
Adiciona um item à fila.
Parâmetros
O valor do item para adicionar à fila.
Tempo de expiração do item, em segundos, após o qual o item será automaticamente removido da fila.
Prioridade do item. Itens com maior prioridade são recuperados da fila antes de itens com menor prioridade.
Devolução
ReadAsync
Lê um ou mais itens da fila como uma única operação atômica.
Este método não exclui automaticamente os itens retornados da fila, mas os torna invisíveis para outras chamadas ReadAsync durante o período do tempo de espera de invisibilidade.Os itens devem ser explicitamente removidos da fila com MemoryStoreQueue:RemoveAsync() antes do tempo de espera de invisibilidade expirar.O tempo limite de invisibilidade padrão é de 30 segundos, a menos que um valor diferente tenha sido fornecido em MemoryStoreService:GetQueue() .
Parâmetros
Número de itens a serem ler. O valor máximo permitido deste parâmetro é 100.
Controla o comportamento do método no caso de a fila ter menos de countO valor padrão é falso.
A duração, em segundos, para a qual o método esperará se o número necessário de itens não estiver imediatamente disponível na fila.Leituras são tentadas a cada dois segundos durante esse período.Este parâmetro pode ser definido como zero para indicar nenhuma espera.Se esse parâmetro não for fornecido ou definido como -1, o método esperará indefinidamente.
Devolução
Um tuple de dois elementos.O primeiro elemento é um array de valores de item lidos da fila.O segundo elemento é um identificador de corda que deve ser passado para MemoryStoreQueue:RemoveAsync() para remover permanentemente esses itens da fila.
Amostras de código
The following code sample demonstrates using MemoryStoreQueue:ReadAsync() and MemoryStoreQueue:RemoveAsync() to reliably read, process, and remove items from a queue. Though this process can be as complicated as necessary, this example simply sets a flag in the corresponding data store item, which guarantees that every item will eventually be processed even if some of the calls encounter errors or the server crashes:
- If MemoryStoreQueue:ReadAsync() fails, no items are retrieved from the queue. An item will be picked up for processing during the next iteration of the loop.
- If MemoryStoreQueue:ReadAsync() succeeds but DataStoreService:UpdateAsync() fails, the item stays invisible until the queue's invisibility timeout expires, causing the item becoming visible again to be returned in a future loop iteration.
- Similarly, if MemoryStoreQueue:RemoveAsync() fails, the item will become visible again in the future and will be processed again.
Depending on where the failure happens, it's possible that an item will be processed more than once. You should account for that like the following code sample, in which the end result is the same even if DataStoreService:UpdateAsync() is invoked multiple times.
local MemoryStoreService = game:GetService("MemoryStoreService")
local DataStoreService = game:GetService("DataStoreService")
local queue = MemoryStoreService:GetQueue("PlayerQueue")
local dataStore = DataStoreService:GetDataStore("PlayerStore")
while true do
pcall(function()
-- wait for an item to process
local items, id = queue:ReadAsync(1, false, 30)
-- check if an item was retrieved
if #items > 0 then
-- mark the item as processed
dataStore:UpdateAsync(items[0], function(data)
data = data or {}
data.processed = 1
return data
end)
-- remove the item from the queue
queue:RemoveAsync(id)
end
end)
end
RemoveAsync
Remove um item ou itens previamente lidos da fila.Este método usa o identificador retornado por MemoryStoreQueue:ReadAsync() para identificar os itens a remover.Se chamado após o tempo de espera de invisibilidade expirar, a chamada não tem efeito.
Parâmetros
Identifica os itens a serem excluir. Use o valor retornado por MemoryStoreQueue:ReadAsync().
Devolução
Amostras de código
The following code sample demonstrates using MemoryStoreQueue:ReadAsync() and MemoryStoreQueue:RemoveAsync() to reliably read, process, and remove items from a queue. Though this process can be as complicated as necessary, this example simply sets a flag in the corresponding data store item, which guarantees that every item will eventually be processed even if some of the calls encounter errors or the server crashes:
- If MemoryStoreQueue:ReadAsync() fails, no items are retrieved from the queue. An item will be picked up for processing during the next iteration of the loop.
- If MemoryStoreQueue:ReadAsync() succeeds but DataStoreService:UpdateAsync() fails, the item stays invisible until the queue's invisibility timeout expires, causing the item becoming visible again to be returned in a future loop iteration.
- Similarly, if MemoryStoreQueue:RemoveAsync() fails, the item will become visible again in the future and will be processed again.
Depending on where the failure happens, it's possible that an item will be processed more than once. You should account for that like the following code sample, in which the end result is the same even if DataStoreService:UpdateAsync() is invoked multiple times.
local MemoryStoreService = game:GetService("MemoryStoreService")
local DataStoreService = game:GetService("DataStoreService")
local queue = MemoryStoreService:GetQueue("PlayerQueue")
local dataStore = DataStoreService:GetDataStore("PlayerStore")
while true do
pcall(function()
-- wait for an item to process
local items, id = queue:ReadAsync(1, false, 30)
-- check if an item was retrieved
if #items > 0 then
-- mark the item as processed
dataStore:UpdateAsync(items[0], function(data)
data = data or {}
data.processed = 1
return data
end)
-- remove the item from the queue
queue:RemoveAsync(id)
end
end)
end