Skip to content

Instantly share code, notes, and snippets.

@kidandcat
Created April 26, 2024 20:40
Show Gist options
  • Save kidandcat/b3581d586e3084757106ecda6fcec5d2 to your computer and use it in GitHub Desktop.
Save kidandcat/b3581d586e3084757106ecda6fcec5d2 to your computer and use it in GitHub Desktop.
Example usage of Olric
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"os"
"strings"
"github.com/buraksezer/olric"
"github.com/buraksezer/olric/config"
)
var port = flag.Int("port", 0, "Port number for this node")
func main() {
flag.Parse()
// local, lan, wan
c := config.New("lan")
c.ReplicaCount = 2
if *port != 0 {
c.Peers = []string{"192.168.68.101:3322"}
c.BindPort = *port
c.MemberlistConfig.BindPort = *port + 1
}
ctx, cancel := context.WithCancel(context.Background())
c.Started = func() {
defer cancel()
log.Println("[INFO] Olric is ready to accept connections")
}
db, err := olric.New(c)
if err != nil {
log.Fatalf("Failed to create Olric instance: %v", err)
}
go func() {
err = db.Start()
if err != nil {
log.Fatalf("olric.Start returned an error: %v", err)
}
}()
<-ctx.Done()
e := db.NewEmbeddedClient()
dm, err := e.NewDMap("bucket-of-arbitrary-items")
if err != nil {
log.Fatalf("olric.NewDMap returned an error: %v", err)
}
// Magic starts here!
ctx, cancel = context.WithCancel(context.Background())
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter ('key' to get or 'key:value' to set): ")
text, _ := reader.ReadString('\n')
values := strings.Split(text, ":")
for i, v := range values {
values[i] = strings.TrimSpace(v)
}
if len(values) == 1 {
gr, err := dm.Get(ctx, values[0])
if err != nil {
log.Printf("Failed to call Get with key %v: %v", values[0], err)
continue
}
value, err := gr.String()
if err != nil {
log.Printf("Failed to read Get response: %v", err)
continue
}
fmt.Println("Response for", values[0], ":", value)
}
if len(values) == 2 {
err = dm.Put(ctx, values[0], values[1])
if err != nil {
log.Printf("Failed to call Put: %v", err)
continue
}
fmt.Println("OK Put", values[0], ":", values[1])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment