我正在学习泄漏的桶算法,并希望通过编写一些带有redis和golang http的简单代码来弄脏我的手。
当我在这里搜索关键字redis,泄漏,桶。[1]中有许多类似的问题,这很好。然而,我发现在浏览了这些线程和wiki之后,我有一个问题来理解整个逻辑[2]。我想有些东西我不明白,也没有意识到这一点。因此,我想在这里再次改写它。如果我弄错了,请纠正我。
伪代码:
key := "ip address, token or anything that can be the representative of a client"
redis_queue_size := 5
interval_between_each_request := 7
request := obtain_http_request_from_somewhere()
if check_current_queue_size() < redis_queue_size:
if is_queue_empty()
add_request_to_the_queue() // zadd "ip1" now() now() // now() is something like seconds, milliseconds or nanoseconds e.g. t = 1
process_request(request)
else
now := get_current_time()
// add_request_to_... retrieves the first element in the queue
// compute the expected timestamp to execute the request and its current time
// e.g. zadd "ip1" <time of the first elment in the queue + interval_between_each_request> now
add_request_to_redis_queue_with_timestamp(now, interval_between_each_request) // e.g. zadd "ip" <timestamp as score> <timestamp a request is allowed to be executed>
// Below function check_the_time_left...() will check how many time left at which the current request need to wait.
// For instance, the first request stored in the queue with the command
// zadd "ip1" 1 1 // t = 1
// and the second request arrives at t = 4 but it is allowed t be executed at t = 8
// zadd "ip1" 8 4 // where 4 := now, 8 := 1 + interval_between_each_request
// so the N will be 4
N := check_the_time_left_for_the_current_request_to_execute(now, interval_between_each_request)
sleep(N) // now the request wait for 4 seconds before processing the request
process_request(http_request_obj)
else
return // discard request
我了解队列已满的部分,然后以下请求将被丢弃。但是,我想我可能会误解当队列未满时,如何重塑传入的请求,以便它可以以固定的速率执行。
慕哥6287543
森栏
相关分类