github.com/songzhibin97/gkit@v1.2.13/distributed/controller/controller_redis/redis_test.go (about)

     1  package controller_redis
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/songzhibin97/gkit/distributed/task"
    10  
    11  	"github.com/go-redis/redis/v8"
    12  	"github.com/songzhibin97/gkit/distributed/broker"
    13  	"github.com/songzhibin97/gkit/distributed/controller"
    14  )
    15  
    16  func InitController() controller.Controller {
    17  	opt := redis.UniversalOptions{
    18  		Addrs: []string{"127.0.0.1:6379"},
    19  	}
    20  	client := redis.NewUniversalClient(&opt)
    21  	if client == nil {
    22  		return nil
    23  	}
    24  	bk := broker.NewBroker(broker.NewRegisteredTask(), context.Background())
    25  	go func() {
    26  		n := 0
    27  		for {
    28  			time.Sleep(time.Second)
    29  			if err := client.LPush(context.Background(), "test_task",
    30  				fmt.Sprintf(`{
    31      "id":"%d",
    32      "name":"test_task"
    33  }`, n)).Err(); err != nil {
    34  				fmt.Println("err:", err)
    35  			}
    36  			n++
    37  		}
    38  	}()
    39  	return NewControllerRedis(bk, client, "test_task", "delayed")
    40  }
    41  
    42  type processor struct{}
    43  
    44  func (p processor) Process(t *task.Signature) error {
    45  	fmt.Println("消费", t.ID, t.Name)
    46  	return nil
    47  }
    48  
    49  func (p processor) ConsumeQueue() string {
    50  	return "test_task"
    51  }
    52  
    53  func (p processor) PreConsumeHandler() bool {
    54  	return false
    55  }
    56  
    57  func TestControllerRedis_StartConsuming(t *testing.T) {
    58  	ct := InitController()
    59  	ct.RegisterTask("test_task")
    60  	go func() {
    61  		time.Sleep(10 * time.Second)
    62  		ct.StopConsuming()
    63  	}()
    64  	b, err := ct.StartConsuming(1, processor{})
    65  	if err != nil {
    66  		t.Error(err)
    67  		return
    68  	}
    69  	t.Log(b)
    70  }