Требуется кэшировать структуру в Memcache
Понадобятся:
- Golang
- Memcache
- Telnet — опционально
Вся идея в том, чтобы превратить структуру в байты с помощью Json.Marshal и сохранить в кеше, затем десериализовать с помощью Json.Unmarshal
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | package main import ( 	"encoding/json" 	"fmt" 	"github.com/bradfitz/gomemcache/memcache" 	"time" ) type Cache struct { 	cache *memcache.Client } func (c *Cache) Set(key string, value []byte, expiration int32) error { 	item := &memcache.Item{ 		Key:        key, 		Value:      value, 		Expiration: expiration, 	} 	return c.cache.Set(item) } func (c *Cache) Get(key string) ([]byte, error) { 	item, err := c.cache.Get(key) 	if err != nil { 		return nil, err 	} 	return item.Value, err } func NewCache() *Cache { 	cacheServer := memcache.New("localhost:11211") 	cacheServer.Timeout = 5 * time.Second 	return &Cache{ 		cache: cacheServer, 	} } type User struct { 	Username string `json:"username"` 	Email    string `json:"email"` 	Age      int    `json:"age"` } func main() { 	cache := NewCache() 	user := &User{ 		Username: "Alma", 		Email:    "alma@alma.test", 		Age:      99, 	} 	value, _ := json.Marshal(user) 	_ = cache.Set("MyKey", value, 30) 	valueFromCache, err := cache.Get("MyKey") 	if err != nil { 		fmt.Println(err) 		return 	} 	userFromCache := new(User) 	err = json.Unmarshal(valueFromCache, userFromCache) 	fmt.Println("Get from cache", userFromCache, err) } | 
localhost:11211 — Хост memcache, 11211 — порт по умолчанию
fmt.Println(«Get from cache», userFromCache, err) выводит
| 1 2 3 4 | PS C:\MyProjects\memcache-test> go run .\memcache.go Get from cache &{Alma alma@alma.test 99} <nil> | 
Также можно посмотреть в самом Memcache через Telnet с помощью команды
| 1 2 3 4 | telnet localhost:11211 gets MyKey | 
Если у вас Windows 10 и не установлен telnet, то нужно сначала загрузить через команду
| 1 2 3 | dism /online /Enable-Feature /FeatureName:TelnetClient | 
 
			
			