Last active
November 6, 2020 20:12
-
-
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
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
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) | |
} |
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
(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