github.com/leslie-fei/fastcache@v0.0.0-20240520092641-b7a9eb05711f/example/main.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "errors" 6 "flag" 7 "fmt" 8 "os" 9 "strings" 10 11 "github.com/leslie-fei/fastcache" 12 "github.com/leslie-fei/fastcache/mmap" 13 ) 14 15 func main() { 16 var size int 17 var key string 18 19 // Example command: go run main.go --port 8080 --multicore=true 20 flag.IntVar(&size, "m", 64, "memory limit unit MB default 64") 21 flag.StringVar(&key, "k", "/tmp/TestSharedMemory", "attach share memory path") 22 flag.Parse() 23 24 size = size * fastcache.MB 25 26 //mem := shm.NewMemory(key, uint64(size), true) 27 mem := mmap.NewMemory(key, uint64(size)) 28 if err := mem.Attach(); err != nil { 29 panic(err) 30 } 31 32 defer func() { 33 if err := mem.Detach(); err != nil { 34 panic(err) 35 } 36 }() 37 38 cache, err := fastcache.NewCache(mem) 39 if err != nil { 40 panic(err) 41 } 42 43 scanner := bufio.NewScanner(os.Stdin) 44 fmt.Println("Available commands: set <key> <value>, get <key>, del <key>, exit") 45 46 for scanner.Scan() { 47 input := scanner.Text() 48 parts := strings.SplitN(input, " ", 3) 49 50 switch parts[0] { 51 case "exit": 52 return 53 case "set": 54 if len(parts) != 3 { 55 fmt.Println("Usage: set <key> <value>") 56 continue 57 } 58 cache.Set(parts[1], []byte(parts[2])) 59 fmt.Println("Set completed.") 60 case "get": 61 if len(parts) != 2 { 62 fmt.Println("Usage: get <key>") 63 continue 64 } 65 result, err := cache.Get(parts[1]) 66 if err != nil && !errors.Is(err, fastcache.ErrNotFound) { 67 panic(err) 68 } 69 70 if errors.Is(err, fastcache.ErrNotFound) { 71 fmt.Println("key not found") 72 continue 73 } 74 75 fmt.Printf("key: %s value: %s\n", parts[1], result) 76 case "del": 77 if len(parts) != 2 { 78 fmt.Println("Usage: del <key>") 79 continue 80 } 81 if err := cache.Del(parts[1]); err != nil { 82 fmt.Println("delete error: ", err) 83 continue 84 } 85 fmt.Println("Del completed.") 86 default: 87 fmt.Println("Unknown command. Try: set, get, del or exit.") 88 } 89 } 90 }