Go语言基于HTTP的内存缓存服务的实现

作者:N3ptune 时间:2024-05-21 10:25:12 

所有的缓存数据都存储在服务器的内存中,因此重启服务器会导致数据丢失,基于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

来源:https://www.cnblogs.com/N3ptune/p/16623738.html

标签:Go,内存,缓存
0
投稿

猜你喜欢

  • Python实现把json格式转换成文本或sql文件

    2022-06-03 14:52:23
  • python实现图片横向和纵向拼接

    2021-12-20 20:53:30
  • 实例解析Python设计模式编程之桥接模式的运用

    2021-06-03 18:48:04
  • 利用Pandas读取某列某行数据之loc和iloc用法总结

    2022-08-18 19:20:58
  • python实现发送邮件

    2021-08-06 04:33:28
  • PHP桥接模式Bridge Pattern的优点与实现过程

    2023-05-25 06:53:44
  • Python动态强类型解释型语言原理解析

    2021-12-24 08:09:27
  • MySQL视图的概念和操作函数详解

    2024-01-24 15:27:22
  • Python通过调用mysql存储过程实现更新数据功能示例

    2024-01-25 11:28:51
  • Python中实现一行拆多行和多行并一行的示例代码

    2021-05-20 12:32:26
  • asp连接MYSQL数据库的连接字符串(参数OPTION)

    2009-03-09 18:24:00
  • Pytorch中torchtext终极安装方法以及常见问题

    2023-03-15 11:59:09
  • JavaScript实现点击按钮复制指定区域文本(推荐)

    2023-08-22 17:36:30
  • Python reshape的用法及多个二维数组合并为三维数组的实例

    2021-12-18 10:29:25
  • Python实现基于SVM的分类器的方法

    2023-11-18 18:20:02
  • Access中的模糊查询

    2007-11-18 14:57:00
  • js正则表达式验证密码强度【推荐】

    2024-04-29 13:39:30
  • 基于keras 模型、结构、权重保存的实现

    2022-12-20 06:31:22
  • mysql 复制过滤重复如何解决

    2024-01-18 17:55:54
  • python3.8下载及安装步骤详解

    2023-11-19 18:47:02
  • asp之家 网络编程 m.aspxhome.com