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()) | |
} |
想问下, 现在clientv3 如果 time.Sleep(2000000000) 换成业务代码 , 中间执行失败了. 导致 m.Unlock(context.TODO()) 没有执行. 这个锁 还会自动释放吗?
这个取决于业务代码执行失败后是怎么处理的,是Log error?Return early?还是直接panic?
但是没错,这个代码并不鲁棒,当时只是为了测试一下etcd。应该在Lock后立即 defer UnLock。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
想问下, 现在clientv3 如果 time.Sleep(2000000000) 换成业务代码 , 中间执行失败了. 导致 m.Unlock(context.TODO()) 没有执行. 这个锁 还会自动释放吗?