Skip to content

Instantly share code, notes, and snippets.

@tom-code
Last active December 17, 2019 21:41
Show Gist options
  • Save tom-code/2718f44e0337d05545aab0e3bdb8fbb7 to your computer and use it in GitHub Desktop.
Save tom-code/2718f44e0337d05545aab0e3bdb8fbb7 to your computer and use it in GitHub Desktop.
raftlib use
package main
import (
"fmt"
"net"
"io"
"github.com/hashicorp/raft"
"time"
"os"
"flag"
)
func main() {
fmt.Println("start")
myselfptr := flag.String("m", "127.0.0.1:7777", "myself")
flag.Parse()
me := *myselfptr
conf := raft.DefaultConfig()
conf.LocalID = raft.ServerID(me)
inmemstore := raft.NewInmemStore()
snapstore := raft.NewInmemSnapshotStore()
ip, _ := net.ResolveTCPAddr("tcp", me)
fmt.Println(ip)
trans, err := raft.NewTCPTransport(me, ip, 10, 2*time.Second, os.Stdout)
if err != nil {
fmt.Println(err)
}
c := []raft.Server{
raft.Server{
Suffrage: raft.Voter,
ID: raft.ServerID("127.0.0.1:7777"),
Address: raft.ServerAddress("127.0.0.1:7777"),
},
raft.Server{
Suffrage: raft.Voter,
ID: raft.ServerID("127.0.0.1:7778"),
Address: raft.ServerAddress("127.0.0.1:7778"),
},
raft.Server{
Suffrage: raft.Voter,
ID: raft.ServerID("127.0.0.1:7779"),
Address: raft.ServerAddress("127.0.0.1:7779"),
},
}
config := raft.Configuration{Servers: c}
err = raft.BootstrapCluster(conf, inmemstore, inmemstore, snapstore, trans, config)
fmt.Println(err)
raf, err := raft.NewRaft(conf, nil, inmemstore, inmemstore, snapstore, trans)
t := time.NewTicker(time.Duration(1) * time.Second)
for {
select {
case <-t.C:
fmt.Println(raf.Leader())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment