Skip to content

Instantly share code, notes, and snippets.

@rossedman
Last active November 6, 2020 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossedman/1b678a55ebd4f86e08fef391ea4c212f to your computer and use it in GitHub Desktop.
Save rossedman/1b678a55ebd4f86e08fef391ea4c212f to your computer and use it in GitHub Desktop.
Consistent hashing server that will determine a key path to write information to across a key space
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/lafikl/consistent"
)
var (
key string
partitions int
)
func init() {
flag.StringVar(&key, "key-path", "kv/test/path", "the path for storage")
flag.IntVar(&partitions, "partitions", 3, "numbers of partitions in keyspace")
flag.Parse()
}
func main() {
// set up consistent hashing
c := consistent.New()
// add keys spaces for hashing
for i := 0; i < partitions; i++ {
c.Add(fmt.Sprintf("%s-%v", key, i))
}
// setup endpoint
r := mux.NewRouter()
r.HandleFunc("/key/{namespace}/{service}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
// get partition and increment load
p, err := c.GetLeast(vars["namespace"])
if err != nil {
log.Println(err)
}
c.Inc(p)
// return
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "%v/%v/%v\n", p, vars["namespace"], vars["service"])
})
http.ListenAndServe(":8080", r)
}
(base) ➜ ~ curl localhost:8080/key/cat-production/service-1
kv/test/path-2/cat-production/service-1
(base) ➜ ~ curl localhost:8080/key/cat-production/service-2
kv/test/path-2/cat-production/service-2
(base) ➜ ~ curl localhost:8080/key/cat-production/service-3
kv/test/path-1/cat-production/service-3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment