gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/sync/README.md (about) 1 # Sync 2 3 Sync is a synchronization library for distributed systems. 4 5 ## Overview 6 7 Distributed systems by their very nature are decoupled and independent. In most cases they must honour 2 out of 3 letters of the CAP theorem 8 e.g Availability and Partitional tolerance but sacrificing consistency. In the case of microservices we often offload this concern to 9 an external database or eventing system. Go Sync provides a framework for synchronization which can be used in the application by the developer. 10 11 ## Getting Started 12 13 - [Leader](#leader) - leadership election for group coordination 14 - [Lock](#lock) - distributed locking for exclusive resource access 15 - [Task](#task) - distributed job execution 16 - [Time](#time) - provides synchronized time 17 18 ## Lock 19 20 The Lock interface provides distributed locking. Multiple instances attempting to lock the same id will block until available. 21 22 ```go 23 import "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/lock/consul" 24 25 lock := consul.NewLock() 26 27 // acquire lock 28 err := lock.Acquire("id") 29 // handle err 30 31 // release lock 32 err = lock.Release("id") 33 // handle err 34 ``` 35 36 ## Leader 37 38 Leader provides leadership election. Useful where one node needs to coordinate some action. 39 40 ```go 41 import ( 42 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/leader" 43 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/leader/consul" 44 ) 45 46 l := consul.NewLeader( 47 leader.Group("name"), 48 ) 49 50 // elect leader 51 e, err := l.Elect("id") 52 // handle err 53 54 55 // operate while leader 56 revoked := e.Revoked() 57 58 for { 59 select { 60 case <-revoked: 61 // re-elect 62 e.Elect("id") 63 default: 64 // leader operation 65 } 66 } 67 68 // resign leadership 69 e.Resign() 70 ``` 71 72 ## Task 73 74 Task provides distributed job execution. It's a simple way to distribute work across a coordinated pool of workers. 75 76 ```go 77 import ( 78 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/task" 79 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/task/local" 80 ) 81 82 t := local.NewTask( 83 task.WithPool(10), 84 ) 85 86 err := t.Run(task.Command{ 87 Name: "atask", 88 Func: func() error { 89 // exec some work 90 return nil 91 }, 92 }) 93 94 if err != nil { 95 // do something 96 } 97 ``` 98 99 ## Time 100 101 Time provides synchronized time. Local machines may have clock skew and time cannot be guaranteed to be the same everywhere. 102 Synchronized Time allows you to decide how time is defined for your applications. 103 104 ```go 105 import ( 106 "gitee.com/liuxuezhan/go-micro-v1.18.0/sync/time/ntp" 107 ) 108 109 110 t := ntp.NewTime() 111 time, err := t.Now() 112 ``` 113 114 ## TODO 115 116 - Event package - strongly consistent event stream e.g kafka