Implement Raft in Our Service
Distributed Services with Go — by Travis Jeffery (58 / 84)
Published in
20 min readApr 23, 2021
👈 What Is Raft and How Does It Work? | TOC | Multiplex to Run Multiple Services on One Por t 👉
We have a log that can write and read records on one computer. We want a distributed log that’s replicated on multiple computers, so let’s implement Raft in our service to get that.
Install Raft by running this command:
$ go get github.com/hashicorp/raft@v1.1.1
$ # use etcd's fork of Ben Johnson's Bolt key/value store,
$ # which includes fixes for Go 1.14+
$ go mod edit -replace github.com/hashicorp/raft-boltdb=\
github.com/travisjeffery/raft-boltdb@v1.0.0
In the internal/log directory, create a distributed.go file, beginning with this snippet:
CoordinateWithConsensus/internal/log/distributed.go
package log
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net"
"os"
"path/filepath"
"time"
raftboltdb "github.com/hashicorp/raft-boltdb"
"google.golang.org/protobuf/proto"
"github.com/hashicorp/raft"
api "github.com/travisjeffery/proglog/api/v1"
)
type DistributedLog struct {
config Config
log *Log
raft *raft.Raft
}
func NewDistributedLog(dataDir string, config Config) (
*DistributedLog…