Fetch the repository succeeded.
package main
import (
"fmt"
"time"
"github.com/micro/go-micro/registry"
"github.com/micro/go-os/sync"
"github.com/micro/go-plugins/sync/etcd"
)
func leaderStatus(i int, s sync.Leader, msg string) {
status, err := s.Status()
if err != nil {
fmt.Printf("[leader:%d] error getting leader status %v", err)
return
}
fmt.Printf("[leader:%d] [status:%v] %s\n", i, status, msg)
}
func acquire(i int, s sync.Sync) {
l, err := s.Lock("alock")
if err != nil {
fmt.Printf("[lock:%d] err acquiring lock interface %v\n", i, err)
return
}
fmt.Printf("[lock:%d] attempting to acquire lock\n", i)
if err := l.Acquire(); err != nil {
fmt.Printf("[lock:%d] err acquiring lock %v\n", i, err)
return
}
fmt.Printf("[lock:%d] acquired lock!\n", i)
time.Sleep(time.Second)
fmt.Printf("[lock:%d] unlocking now\n", i)
if err := l.Release(); err != nil {
fmt.Printf("[lock:%d] err releasing lock %v\n", i, err)
}
fmt.Printf("[lock:%d] unlocked\n", i)
}
func leader(i int, s sync.Sync) {
// Get a leader interface
l, err := s.Leader("king")
if err != nil {
fmt.Printf("[leader:%d] err acquiring leader interface %v\n", i, err)
return
}
leader, err := l.Leader()
if err != nil {
fmt.Printf("[leader:%d] err getting current leader %v\n", i, err)
leaderStatus(i, l, "attempting to elect self")
} else {
leaderStatus(i, l, fmt.Sprintf("attempting to elect self. current leader %v", leader))
}
// Attempt to elect self
throne, err := l.Elect()
if err != nil {
fmt.Printf("[leader:%d] err electing self %v\n", i, err)
return
}
leaderStatus(i, l, "elected as leader")
j := 0
revoked, err := throne.Revoked()
if err != nil {
fmt.Printf("[leader:%d] throne already revoked, gnarly %v\n", i, err)
}
loop:
for {
select {
// Check if we've been revoked
case <-revoked:
leaderStatus(i, l, "leadership revoked")
return
default:
leaderStatus(i, l, "I'm leading son")
time.Sleep(time.Second)
}
if j >= 3 {
break loop
}
j++
}
leader, err = l.Leader()
if err != nil {
fmt.Printf("[leader:%d] err getting current leader %v\n", i, err)
} else {
leaderStatus(i, l, fmt.Sprintf("current leader %v", leader))
}
leaderStatus(i, l, "resigning now")
// Resign leadership status
if err := throne.Resign(); err != nil {
leaderStatus(i, l, fmt.Sprintf("err resigning %v", err))
}
leaderStatus(i, l, "resigned")
}
func main() {
// using etcd
newfn := etcd.NewSync
// Acquire locks
for i := 0; i < 2; i++ {
go acquire(i, newfn())
}
acquire(2, newfn())
// Acquire leadership
for i := 0; i < 2; i++ {
go leader(i, newfn(
sync.Service(®istry.Service{
Name: "foo",
Version: "latest",
Nodes: []*registry.Node{®istry.Node{Id: fmt.Sprintf("foo-%d", i)}},
}),
))
}
leader(2, newfn(
sync.Service(®istry.Service{
Name: "foo",
Version: "latest",
Nodes: []*registry.Node{®istry.Node{Id: "foo-2"}},
}),
))
// Sleep just for fun
time.Sleep(time.Second * 5)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。