Created
May 15, 2018 05:02
-
-
Save chenminhua/2a5b9823833b7f96084bf4993a32081c to your computer and use it in GitHub Desktop.
基于etcd的分布式锁
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
c, err := clientv3.New(clientv3.Config{ | |
Endpoints: []string{"ip:port"}, | |
DialTimeout: 5 * time.Second, | |
}) | |
if err != nil { | |
panic(err) | |
} | |
lockKey := "/lock" | |
session, err := concurrency.NewSession(c) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("locking") | |
m := concurrency.NewMutex(session, lockKey) | |
if err := m.Lock(context.TODO()); err != nil { | |
panic(err) | |
} | |
fmt.Println(m) | |
time.Sleep(2000000000) | |
fmt.Println("unlocking") | |
m.Unlock(context.TODO()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
这个取决于业务代码执行失败后是怎么处理的,是Log error?Return early?还是直接panic?
但是没错,这个代码并不鲁棒,当时只是为了测试一下etcd。应该在Lock后立即 defer UnLock。