package lock

import (
	"context"
	"github.com/redis/go-redis/v9"
	"sync"
	"testing"
	"time"
)

func TestMutex(t *testing.T) {
	client := redis.NewClient(&redis.Options{
		Addr:     "192.168.6.75:6379",
		Password: "lansexiongdi",
		DB:       2,
	})
	defer client.Close()
	ctx := context.Background()
	key := "wechat_access_token:appid"
	var token string
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		defer wg.Done()
		err := NewMutex(client, time.Second*30).Lock(ctx, key, func(ctx context.Context) error {
			t.Log("go1 start, time:", time.Now().String())
			time.Sleep(time.Second * 2)
			token = "123456"
			t.Log("go1 end, time:", time.Now().String())
			return nil
		})
		if err != nil {
			t.Error(err)
		} else {
			t.Log("success,token", token, time.Now().String())
		}
	}()
	go func() {
		defer wg.Done()
		err := NewMutex(client, time.Second*30).Lock(ctx, key, func(ctx context.Context) error {
			t.Log("go2 start, time:", time.Now().String())
			time.Sleep(time.Second * 10)
			token = "123456789"
			t.Log("go2 end, time:", time.Now().String())
			return nil
		})
		if err != nil {
			t.Error(err)
		} else {
			t.Log("success,token", token, time.Now().String())
		}
	}()
	wg.Wait()
}
