2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-12-25 23:32:17 +08:00
asynq/README.md

253 lines
8.2 KiB
Markdown
Raw Normal View History

2020-01-06 01:06:23 +08:00
# Asynq
2020-01-21 07:17:41 +08:00
[![Build Status](https://travis-ci.com/hibiken/asynq.svg?token=paqzfpSkF4p23s5Ux39b&branch=master)](https://travis-ci.com/hibiken/asynq)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Go Report Card](https://goreportcard.com/badge/github.com/hibiken/asynq)](https://goreportcard.com/report/github.com/hibiken/asynq)
[![GoDoc](https://godoc.org/github.com/hibiken/asynq?status.svg)](https://godoc.org/github.com/hibiken/asynq)
[![Gitter chat](https://badges.gitter.im/go-asynq/gitter.svg)](https://gitter.im/go-asynq/community)
2020-02-20 13:37:54 +08:00
[![codecov](https://codecov.io/gh/hibiken/asynq/branch/master/graph/badge.svg)](https://codecov.io/gh/hibiken/asynq)
2019-12-01 01:38:46 +08:00
2020-04-12 07:33:35 +08:00
## Overview
2020-04-12 07:33:35 +08:00
Asynq is a Go library for queueing tasks and processing them in the background with workers. It is backed by Redis and it is designed to have a low barrier to entry. It should be integrated in your web stack easily.
Highlevel overview of how Asynq works:
- Client puts task on a queue
- Server pulls task off queues and starts a worker goroutine for each task
- Workers process tasks concurrently
Task queues are used as a mechanism to distribute work across multiple machines.
A system can consist of multiple worker servers and brokers, giving way to high availability and horizontal scaling.
![Task Queue Diagram](/docs/assets/overview.png)
2019-12-01 01:38:46 +08:00
## Stability and Compatibility
**Important Note**: Current major version is zero (v0.x.x) to accomodate rapid development and fast iteration while getting early feedback from users. The public API could change without a major version update before v1.0.0 release.
**Status**: The library is currently undergoing heavy development with frequent, breaking API changes.
2020-03-28 23:37:50 +08:00
## Features
- Guaranteed at least one execution of a task
- Scheduling of tasks
- Durability since tasks are written to Redis
- Retries of failed tasks
- Concurrency management via configuration
- Weighted priority queues
- Strict priority queues
- Low latency to add a task since writes are fast in Redis
- De-duplication of tasks using unique option
- Allow timeout and deadline per task
- Flexible handler interface with support for middlewares
- CLI to inspect and remote-control queues and tasks
2020-02-06 13:58:05 +08:00
## Quickstart
2020-01-21 07:17:41 +08:00
2020-01-27 11:58:48 +08:00
First, make sure you are running a Redis server locally.
2020-01-23 22:33:34 +08:00
```sh
2020-02-07 22:45:36 +08:00
$ redis-server
2020-01-23 22:33:34 +08:00
```
2020-03-24 01:35:17 +08:00
Next, write a package that encapsulates task creation and task handling.
```go
2020-03-15 06:51:23 +08:00
package tasks
import (
"fmt"
"github.com/hibiken/asynq"
)
// A list of background task types.
const (
EmailDelivery = "email:deliver"
ImageProcessing = "image:process"
)
// Write function NewXXXTask to create a task.
func NewEmailDeliveryTask(userID int, tmplID string) *asynq.Task {
payload := map[string]interface{}{"user_id": userID, "template_id": tmplID}
return asynq.NewTask(EmailDelivery, payload)
}
func NewImageProcessingTask(src, dst string) *asynq.Task {
payload := map[string]interface{}{"src": src, "dst": dst}
return asynq.NewTask(ImageProcessing, payload)
}
// Write function HandleXXXTask to handle the given task.
// NOTE: It satisfies the asynq.HandlerFunc interface.
func HandleEmailDeliveryTask(ctx context.Context, t *asynq.Task) error {
userID, err := t.Payload.GetInt("user_id")
if err != nil {
return err
}
tmplID, err := t.Payload.GetString("template_id")
if err != nil {
return err
2020-01-27 11:58:48 +08:00
}
2020-03-15 06:51:23 +08:00
fmt.Printf("Send Email to User: user_id = %d, template_id = %s\n", userID, tmplID)
// Email delivery logic ...
return nil
}
2020-03-15 06:51:23 +08:00
func HandleImageProcessingTask(ctx context.Context, t *asynq.Task) error {
src, err := t.Payload.GetString("src")
if err != nil {
return err
}
dst, err := t.Payload.GetString("dst")
if err != nil {
return err
}
fmt.Printf("Process image: src = %s, dst = %s\n", src, dst)
// Image processing logic ...
return nil
}
```
In your web application code, import the above package and use [`Client`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Client) to enqueue tasks to the task queue.
A task will be processed by a background worker as soon as the task gets enqueued.
Scheduled tasks will be stored in Redis and will be enqueued at the specified time.
```go
package main
import (
"time"
"github.com/hibiken/asynq"
"your/app/package/tasks"
)
const redisAddr = "127.0.0.1:6379"
func main() {
r := &asynq.RedisClientOpt{Addr: redisAddr}
2020-03-14 05:50:03 +08:00
c := asynq.NewClient(r)
2019-12-01 01:38:46 +08:00
2020-03-14 05:50:03 +08:00
// Example 1: Enqueue task to be processed immediately.
2020-03-15 06:51:23 +08:00
t := tasks.NewEmailDeliveryTask(42, "some:template:id")
2020-03-14 05:50:03 +08:00
err := c.Enqueue(t)
if err != nil {
log.Fatal("could not enqueue task: %v", err)
2020-03-15 06:51:23 +08:00
}
2019-12-01 01:38:46 +08:00
2020-01-23 22:33:34 +08:00
2020-03-14 05:50:03 +08:00
// Example 2: Schedule task to be processed in the future.
2020-01-23 22:33:34 +08:00
2020-03-15 06:51:23 +08:00
t = tasks.NewEmailDeliveryTask(42, "other:template:id")
2020-03-14 05:50:03 +08:00
err = c.EnqueueIn(24*time.Hour, t)
if err != nil {
log.Fatal("could not schedule task: %v", err)
}
2020-03-15 06:51:23 +08:00
// Example 3: Pass options to tune task processing behavior.
2020-03-14 05:50:03 +08:00
// Options include MaxRetry, Queue, Timeout, Deadline, etc.
2020-03-15 06:51:23 +08:00
t = tasks.NewImageProcessingTask("some/blobstore/url", "other/blobstore/url")
2020-03-14 05:50:03 +08:00
err = c.Enqueue(t, asynq.MaxRetry(10), asynq.Queue("critical"), asynq.Timeout(time.Minute))
if err != nil {
log.Fatal("could not enqueue task: %v", err)
}
2020-01-23 22:33:34 +08:00
}
```
2020-03-15 06:51:23 +08:00
Next, create a binary to process these tasks in the background.
To start the background workers, use [`Background`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Background) and provide your [`Handler`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Handler) to process the tasks.
2019-12-01 01:38:46 +08:00
2020-03-15 06:51:23 +08:00
You can optionally use [`ServeMux`](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#ServeMux) to create a handler, just as you would with [`"net/http"`](https://golang.org/pkg/net/http/) Handler.
```go
2020-03-15 06:51:23 +08:00
package main
2020-03-15 06:51:23 +08:00
import (
"github.com/hibiken/asynq"
"your/app/package/tasks"
)
const redisAddr = "127.0.0.1:6379"
2019-12-01 01:38:46 +08:00
func main() {
2020-03-15 06:51:23 +08:00
r := &asynq.RedisClientOpt{Addr: redisAddr}
2019-12-01 01:38:46 +08:00
2020-01-27 11:58:48 +08:00
bg := asynq.NewBackground(r, &asynq.Config{
// Specify how many concurrent workers to use
Concurrency: 10,
// Optionally specify multiple queues with different priority.
Queues: map[string]int{
2020-01-27 11:58:48 +08:00
"critical": 6,
"default": 3,
"low": 1,
},
// See the godoc for other configuration options
})
2019-12-01 01:38:46 +08:00
// mux maps a type to a handler
mux := asynq.NewServeMux()
2020-03-15 06:51:23 +08:00
mux.HandleFunc(tasks.EmailDelivery, tasks.HandleEmailDeliveryTask)
mux.HandleFunc(tasks.ImageProcessing, tasks.HandleImageProcessingTask)
// ...register other handlers...
2019-12-28 08:26:11 +08:00
bg.Run(mux)
}
2019-12-28 08:26:11 +08:00
```
2020-01-27 11:58:48 +08:00
For a more detailed walk-through of the library, see our [Getting Started Guide](https://github.com/hibiken/asynq/wiki/Getting-Started).
2020-01-23 22:33:34 +08:00
To Learn more about `asynq` features and APIs, see our [Wiki](https://github.com/hibiken/asynq/wiki) and [godoc](https://godoc.org/github.com/hibiken/asynq).
2020-01-21 07:17:41 +08:00
2020-01-23 22:33:34 +08:00
## Command Line Tool
2020-01-23 22:33:34 +08:00
Asynq ships with a command line tool to inspect the state of queues and tasks.
2020-01-19 12:31:22 +08:00
Here's an example of running the `stats` command.
![Gif](/docs/assets/demo.gif)
For details on how to use the tool, refer to the tool's [README](/tools/asynqmon/README.md).
## Installation
To install `asynq` library, run the following command:
```sh
go get -u github.com/hibiken/asynq
```
To install the CLI tool, run the following command:
2020-01-19 12:31:22 +08:00
2020-02-07 22:45:36 +08:00
```sh
go get -u github.com/hibiken/asynq/tools/asynqmon
```
2020-01-19 12:31:22 +08:00
## Requirements
| Dependency | Version |
| -------------------------- | ------- |
| [Redis](https://redis.io/) | v2.8+ |
| [Go](https://golang.org/) | v1.13+ |
2020-02-09 01:34:14 +08:00
## Contributing
We are open to, and grateful for, any contributions (Github issues/pull-requests, feedback on Gitter channel, etc) made by the community.
Please see the [Contribution Guide](/CONTRIBUTING.md) before contributing.
2020-01-06 01:06:23 +08:00
## Acknowledgements
- [Sidekiq](https://github.com/mperham/sidekiq) : Many of the design ideas are taken from sidekiq and its Web UI
2020-02-24 12:43:24 +08:00
- [RQ](https://github.com/rq/rq) : Client APIs are inspired by rq library.
2020-01-06 01:06:23 +08:00
- [Cobra](https://github.com/spf13/cobra) : Asynqmon CLI is built with cobra
2019-12-28 08:26:11 +08:00
## License
Asynq is released under the MIT license. See [LICENSE](https://github.com/hibiken/asynq/blob/master/LICENSE).