Skip to content

A priority queue based on Redis with a time complexity of O(1). It is suitable for those dining order queues where there are priority requirements, but it can also be used by those without such requirements。(一个基于redis、时间复杂度为O(1)的优先级队列。适合那些有优先级需求的点餐排队,当然,没有优先级需求的也能用。)

Notifications You must be signed in to change notification settings

asjfoajs/go-redis-priority

Repository files navigation

中文文档

Introduction

A priority queue implemented based on Redis. Compared to using zset, each method here operates in O(1) time complexity. It is suitable for scenarios such as ordering food and number calling or appointment registration. For more details, please refer to: Develop a priority queue with a time complexity of O(1) based on Redis.

How to Use?

Please refer to the priority_queue_test.go file.

  1. Initialize the redis.Client
func newTestClient() *redis.Client {
    // Use DB 0 as the test database
    client := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        DB: 0,
    })
    // Clear the test database
    _, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    //if err := client.FlushDB(ctx).Err(); err != nil {
    //    fmt.Fprintf(os.Stderr, "FlushDB error: %v\n", err)
    //    os.Exit(1)
    //}
    return client
}
  1. Create a Priority Queue
client := newTestClient()
baseKey := "test:queue:pushpop"
// Create three priority levels (levels 1 through 3)
pq := NewPriorityQueue(baseKey, 3, 5, 1, 10, client)
defer pq.Stop()
  1. Add an Element
// Define a test element
elemA := Element{ID: "a", Value: "A-value"}

// Push: Insert elemA into priority level 1 (and similarly, you can insert other elements like elemB or elemC into different levels)
if err := pq.Push(1, elemA); err != nil {
    t.Fatalf("Push failed: %v", err)
}
  1. Get the Number of People Ahead of the Current User
countA, err := pq.CountBefore("a")
if err != nil {
    t.Fatalf("CountBefore for elemA failed: %v", err)
}
  1. Delete
elem, err := pq.Pop()
if err != nil {
    t.Fatalf("Pop failed: %v", err)
}
  1. Get and Remove the Head Element
if err := pq.Pull("a"); err != nil {
    t.Fatalf("Pull failed: %v", err)
}

About

A priority queue based on Redis with a time complexity of O(1). It is suitable for those dining order queues where there are priority requirements, but it can also be used by those without such requirements。(一个基于redis、时间复杂度为O(1)的优先级队列。适合那些有优先级需求的点餐排队,当然,没有优先级需求的也能用。)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published