github.com/aaabigfish/gopkg@v1.1.0/mq/asynq/writer.go (about)

     1  package asynq
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"sync"
     7  
     8  	"github.com/hibiken/asynq"
     9  )
    10  
    11  var (
    12  	once   sync.Once
    13  	client *asynq.Client
    14  )
    15  
    16  type Client = asynq.Client
    17  type TaskInfo = asynq.TaskInfo
    18  
    19  type Writer interface {
    20  	Send(key string, val interface{}, opts ...asynq.Option) (*TaskInfo, error)
    21  	Push(val interface{}, opts ...asynq.Option) (*TaskInfo, error)
    22  	GetWriter() *asynq.Client
    23  	Close() error
    24  }
    25  
    26  type writer struct {
    27  	client *Client
    28  	c      *RedisClientOpt
    29  	topic  string
    30  }
    31  
    32  func NewWriter(con *RedisClientOpt, topic ...string) Writer {
    33  	w := &writer{
    34  		c: con,
    35  	}
    36  	once.Do(func() {
    37  		client = asynq.NewClient(w.c)
    38  	})
    39  	w.client = client
    40  
    41  	if len(topic) > 0 {
    42  		w.topic = topic[0]
    43  	}
    44  
    45  	return w
    46  }
    47  
    48  func (w *writer) GetWriter() *Client {
    49  	return w.client
    50  }
    51  
    52  func (w *writer) Send(key string, val interface{}, opts ...asynq.Option) (*TaskInfo, error) {
    53  	if w.client == nil {
    54  		return nil, errors.New("connection is closed")
    55  	}
    56  
    57  	payload, err := json.Marshal(val)
    58  	if err != nil {
    59  		return nil, err
    60  	}
    61  	task := asynq.NewTask(key, payload, opts...)
    62  
    63  	return w.client.Enqueue(task)
    64  }
    65  
    66  func (w *writer) Push(val interface{}, opts ...asynq.Option) (*TaskInfo, error) {
    67  	if w.topic == "" {
    68  		return nil, errors.New("topic is empty")
    69  	}
    70  
    71  	return w.Send(w.topic, val, opts...)
    72  }
    73  
    74  func (w *writer) Close() error {
    75  	if w.client != nil {
    76  		return w.client.Close()
    77  	}
    78  	return nil
    79  }