lock_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. package redislock
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. "time"
  7. )
  8. func TestLock(t *testing.T) {
  9. lock, err := NewLock("localhost:30379", "mtyzxhc", 0)
  10. if err != nil {
  11. t.Fatal(err)
  12. }
  13. defer func(lock *Lock) {
  14. err := DestroyLock(lock)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. }(lock)
  19. wg := sync.WaitGroup{}
  20. wg.Add(5)
  21. for i := 0; i < 5; i++ {
  22. go func(index int) {
  23. err := lock.Lock("test", "test", 60)
  24. if err != nil {
  25. panic(err)
  26. }
  27. fmt.Println("Lock: ", index, "Time: ", time.Now())
  28. time.Sleep(1 * time.Second)
  29. err = lock.Unlock("test", "test")
  30. if err != nil {
  31. panic(err)
  32. }
  33. fmt.Println("Unlock: ", index, "Time: ", time.Now())
  34. wg.Done()
  35. }(i)
  36. }
  37. wg.Wait()
  38. }
  39. func TestTryLock(t *testing.T) {
  40. lock, err := NewLock("localhost:30379", "mtyzxhc", 0)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. defer func(lock *Lock) {
  45. err := DestroyLock(lock)
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. }(lock)
  50. wg := sync.WaitGroup{}
  51. wg.Add(2)
  52. go func() {
  53. err := lock.Lock("test", "test", 60)
  54. if err != nil {
  55. panic(err)
  56. }
  57. fmt.Println("Lock: ", 1, "Time: ", time.Now())
  58. time.Sleep(6 * time.Second)
  59. err = lock.Unlock("test", "test")
  60. if err != nil {
  61. panic(err)
  62. }
  63. fmt.Println("Unlock: ", 1, "Time: ", time.Now())
  64. wg.Done()
  65. }()
  66. time.Sleep(1 * time.Second)
  67. go func() {
  68. for {
  69. locked, err := lock.TryLock("test", "test", 60)
  70. if err != nil {
  71. panic(err)
  72. }
  73. if !locked {
  74. fmt.Println("TryLock Failed: ", 2, "Time: ", time.Now())
  75. time.Sleep(1 * time.Second)
  76. continue
  77. }
  78. fmt.Println("Lock: ", 2, "Time: ", time.Now())
  79. err = lock.Unlock("test", "test")
  80. if err != nil {
  81. panic(err)
  82. }
  83. fmt.Println("Unlock: ", 2, "Time: ", time.Now())
  84. break
  85. }
  86. wg.Done()
  87. }()
  88. wg.Wait()
  89. }