本篇内容介绍了“Go语言基于HTTP的内存缓存服务怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
所有的缓存数据都存储在服务器的内存中,因此重启服务器会导致数据丢失,基于HTTP通信会将使开发变得简单,但性能不会太好
缓存服务接口
本程序采用REST接口,支持设置(Set)、获取(Get)和删除(Del)这3个基本操作,同时还支持对缓存服务状态进行查询。Set操作是将一对键值对设置到服务器中,通过HTTP的PUT方法进行,Get操作用于查询某个键并获取其值,通过HTTP的GET方法进行,Del操作用于从缓存中删除某个键,通过HTTP的DELETE方法进行,同时用户可以查询缓存服务器缓存了多少键值对,占据了多少字节
创建一个cache包,编写缓存服务的主要逻辑
先定义了一个Cache接口类型,包含了要实现的4个方法(设置、获取、删除和状态查询)
package cache
type Cache interface {
    Set(string, []byte) error
    Get(string) ([]byte, error)
    Del(string) error
    GetStat() Stat
}缓存服务实现
综上所述,这个缓存服务实现起来还是比较容易的,使用Go语言内置的map存储键值,使用http库来处理HTTP请求,实现REST接口
定义状态信息
定义了一个Stat结构体,表示缓存服务状态:
type Stat struct {
    Count     int64
    KeySize   int64
    ValueSize int64
}Count表示缓存目前保存的键值对数量,KeySize和ValueSize分别表示键和值所占的总字节数
实现两个方法,用来更新Stat信息:
func (s *Stat) add(k string, v []byte) {
    s.Count += 1
    s.KeySize += int64(len(k))
    s.ValueSize += int64(len(v))
}
func (s *Stat) del(k string, v []byte) {
    s.Count -= 1
    s.KeySize -= int64(len(k))
    s.ValueSize -= int64(len(v))
}缓存增加键值数据时,调用add函数,更新缓存状态信息,对应地,删除数据时就调用del,保持状态信息的正确
实现Cache接口
下面定义一个New函数,创建并返回一个Cache接口:
func New(typ string) Cache {
    var c Cache
    if typ == "inmemory" {
        c = newInMemoryCache()
    }
    if c == nil {
        panic("unknown cache type " + typ)
    }
    log.Println(typ, "ready to serve")
    return c
}该函数会接收一个string类型的参数,这个参数指定了要创建的Cache接口的具体结构类型,这里考虑到以后可能不限于内存缓存,有扩展的可能。如果typ是"inmemory"代表是内存缓存,就调用newInMemoryCache,并返回
如下定义了inMemoryCache结构和对应New函数:
type inMemoryCache struct {
    c     map[string][]byte
    mutex sync.RWMutex
    Stat
}
 
func newInMemoryCache() *inMemoryCache {
    return &inMemoryCache{
        make(map[string][]byte),
        sync.RWMutex{}, Stat{}}
}这个结构中包含了存储数据的map,和一个读写锁用于并发控制,还有一个Stat匿名字段,用来记录缓存状态
下面一一实现所定义的接口方法:
func (c *inMemoryCache) Set(k string, v []byte) error {
    c.mutex.Lock()
    defer c.mutex.Unlock()
    tmp, exist := c.c[k]
    if exist {
        c.del(k, tmp)
    }
    c.c[k] = v
    c.add(k, v)
    return nil
}
 
func (c *inMemoryCache) Get(k string) ([]byte, error) {
    c.mutex.RLock()
    defer c.mutex.RLock()
    return c.c[k], nil
}
 
func (c *inMemoryCache) Del(k string) error {
    c.mutex.Lock()
    defer c.mutex.Unlock()
    v, exist := c.c[k]
    if exist {
        delete(c.c, k)
        c.del(k, v)
    }
    return nil
}
 
func (c *inMemoryCache) GetStat() Stat {
    return c.Stat
}Set函数的作用是设置键值到map中,这要在上锁的情况下进行,首先判断map中是否已有此键,之后用新值覆盖,过程中要更新状态信息
Get函数的作用是获取指定键对应的值,使用读锁即可
Del同样须要互斥,先判断map中是否有指定的键,如果有则删除,并更新状态信息
实现HTTP服务
接下来实现HTTP服务,基于Go语言的标准HTTP包来实现,在目录下创建一个http包
先定义Server相关结构、监听函数和New函数:
type Server struct {
    cache.Cache
}
 
func (s *Server) Listen() error {
    http.Handle("/cache/", s.cacheHandler())
    http.Handle("/status", s.statusHandler())
    err := http.ListenAndServe(":9090", nil)
    if err != nil {
        log.Println(err)
        return err
    }
    return nil
}
 
func New(c cache.Cache) *Server {
    return &Server{c}
}Server结构体内嵌了cache.Cache接口,这意味着http.Server也要实现对应接口,为Server定义了一个Listen方法,其中会调用http.Handle函数,会注册两个Handler分别用来处理/cache/和status这两个http协议的端点
Server.cacheHandler和http.statusHandler返回一个http.Handler接口,用于处理HTTP请求,相关实现如下:
要实现http.Handler接口就要实现ServeHTTP方法,是真正处理HTTP请求的逻辑,该方法使用switch-case对请求方式进行分支处理,处理PUT、GET、DELETE请求,其他都丢弃
package http
 
import (
    "io/ioutil"
    "log"
    "net/http"
    "strings"
)
 
type cacheHandler struct {
    *Server
}
 
func (h *cacheHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    key := strings.Split(r.URL.EscapedPath(), "/")[2]
    if len(key) == 0 {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    switch r.Method {
    case http.MethodPut:
        b, _ := ioutil.ReadAll(r.Body)
        if len(b) != 0 {
            e := h.Set(key, b)
            if e != nil {
                log.Println(e)
                w.WriteHeader(http.StatusInternalServerError)
            }
        }
        return
    case http.MethodGet:
        b, e := h.Get(key)
        if e != nil {
            log.Println(e)
            w.WriteHeader(http.StatusInternalServerError)
            return
        }
        if len(b) == 0 {
            w.WriteHeader(http.StatusNotFound)
            return
        }
        w.Write(b)
        return
    case http.MethodDelete:
        e := h.Del(key)
        if e != nil {
            log.Println(e)
            w.WriteHeader(http.StatusInternalServerError)
        }
        return
    default:
        w.WriteHeader(http.StatusMethodNotAllowed)
    }
}
 
func (s *Server) cacheHandler() http.Handler {
    return &cacheHandler{s}
}同理,statusHandler实现如下:
package http
 
import (
    "encoding/json"
    "log"
    "net/http"
)
 
type statusHandler struct {
    *Server
}
 
func (h *statusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodGet {
        w.WriteHeader(http.StatusMethodNotAllowed)
        return
    }
    b, e := json.Marshal(h.GetStat())
    if e != nil {
        log.Println(e)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.Write(b)
}
 
func (s *Server) statusHandler() http.Handler {
    return &statusHandler{s}
}该方法只处理GET请求,调用GetStat方法得到缓存状态信息,将其序列化为JSON数据后写回
测试运行
编写一个main.main,作为程序的入口:
package main
import (
    "cache/cache"
    "cache/http"
    "log"
)
 
func main() {
    c := cache.New("inmemory")
    s := http.New(c)
    err := s.Listen()
    if err != nil {
        log.Fatalln(err)
    }
}发起PUT请求,增加数据:
$ curl -v localhost:9090/cache/key -XPUT -d value * Trying 127.0.0.1:9090... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 9090 (#0) > PUT /cache/key HTTP/1.1 > Host: localhost:9090 > User-Agent: curl/7.68.0 > Accept: */* > Content-Length: 5 > Content-Type: application/x-www-form-urlencoded > * upload completely sent off: 5 out of 5 bytes * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Date: Thu, 25 Aug 2022 03:19:47 GMT < Content-Length: 0 < * Connection #0 to host localhost left intact
查看状态信息:
$ curl localhost:9090/status
{"Count":1,"KeySize":3,"ValueSize":5}查询:
$ curl localhost:9090/cache/key value