在 Go 中使用接口进行灵活缓存

开发 后端
Go 中的接口有助于构建灵活的库和应用程序。在本篇文章中,我们将了解 Go 的接口如何帮助构建灵活、可扩展的缓存。

缓存是编程中一种常见的技术,通过存储昂贵的计算或 IO 结果来快速查找,从而提高性能。在本篇文章中,我们将了解 Go 的接口如何帮助构建灵活、可扩展的缓存。

定义缓存接口

首先,让我们定义一个接口,指定缓存功能:

type Cache interface {
  Get(key string) interface{}
  Set(key string, value interface{})
}

缓存接口有两个方法:Get 用于按键查找缓存值,Set 用于存储键值对。

通过定义接口,我们将缓存的使用与特定的实现分离开来。任何实现了这些方法的缓存库都满足接口的要求。

简单的内存缓存

让我们实现一个符合接口的简单内存缓存:

type InMemoryCache struct {
 m     sync.Mutex
 store map[string]interface{}
}

func NewMemoryCache() *InMemoryCache {
 return &InMemoryCache{
  m:     sync.Mutex{},
  store: make(map[string]interface{}),
 }
}

func (c *InMemoryCache) Get(key string) interface{} {
 return c.store[key]
}

func (c *InMemoryCache) Set(key string, value interface{}) {
 c.m.Lock()
 defer c.m.Unlock()
 c.store[key] = value
}

InMemoryCache 使用 map 在内存中存储条目,并且使用 sync.Mutex 来避免并发写的发生。它实现了 Get 和 Set 方法来管理映射中的条目。

使用缓存

现在我们可以轻松使用缓存了:

mc := NewMemoryCache()
mc.Set("hello", "world")
mc.Get("hello") // world

通过该接口,我们可以调用 Set 和 Get,而不必担心实现问题。

其他缓存实现

现在,假设我们想使用 Redis 而不是内存缓存。我们可以创建一个实现相同接口的 RedisCache:

type RedisCache struct {
 client *redis.Client
}

func NewRedisCache() *RedisCache {
 c := &RedisCache{client: redis.NewClient(&redis.Options{
  Addr: "localhost:6379",
 })}
 return c
}

func (c *RedisCache) Get(key string) interface{} {
 ctx := context.Background()
 return c.client.Get(ctx, key)
}

func (c *RedisCache) Set(key string, value interface{}) {
 ctx := context.Background()
 c.client.Set(ctx, key, value, -1)
}

使用方式:

rc := NewRedisCache()
rc.Set("hello", "world")
rc.Get("hello") // world

客户端代码保持不变。这就体现了接口的灵活性。

基于接口的缓存的好处

  • 解耦 - 客户端代码无需与特定的缓存库相耦合。
  • 可维护性--无需修改客户端代码即可更改缓存实现。
  • 可测试性--可对缓存进行存根测试或模拟测试。
  • 可重用性--通用缓存接口允许编写可重用的缓存逻辑。

加料

这里我们看到上面的代码,有两个缓存器,也都实现了 Set 和 Get 方法,但是我们初始化的时候是初始化一个真正的对象:InMemoryCache 和 RedisCache 。实际上我们可以定义一个 cache 接口:

type cache interface {
 Set(key string, value interface{})
 Get(key string) interface{}
}

func DefaultCache() cache {
 return NewMemoryCache()
}

func NewCache(tp string) (cache, error) {
 switch tp {
 case "redis":
  return NewRedisCache(), nil
 default:
  return DefaultCache(), nil
 }
 return nil, errors.New("can not found target cache")
}

这样当我们又有其他缓存器需求时,我们实际上无需再更改客户端的代码,只需要增加 cache 的实现即可。这样改造之后,我们的客户端调用就可以变成这样:

func main() {
 c, err := NewCache("")
 if err != nil {
  log.Fatalln(err)
 }
 c.Set("hello", "world")
 c.Get("hello")
}

我们使用的对象并不是真正的缓存器对象,而是 cache 接口,而 InMemoryCache 和 RedisCache 都实现了 cache 接口,所以我们调用 Set 和 Get 方法的时候,实际上是对应到缓存器真正的实现。

最后

Go 中的接口有助于构建灵活的库和应用程序。定义简单的接口使代码更整洁:

  • 模块化 - 可以插入不同的实现。
  • 可扩展 - 可以不间断地添加新的实现。
  • 可维护 - 组件可以互换,便于维护。
  • 可测试 - 可对组件单独的单元测试。

通过以最小的开销提供强大的抽象,接口在 Golang 中对于创建松散耦合和可扩展的系统非常重要。

责任编辑:赵宁宁 来源: 爱发白日梦的后端
相关推荐

2021-11-29 22:59:34

Go Dockertest集成

2023-11-27 19:39:46

Goprotobuf

2009-03-20 13:40:15

JDK线程并发

2024-02-04 00:00:00

Go货币接口

2024-02-07 11:44:20

NestJSRxJS异步编程

2011-12-08 10:24:53

JavaNIO

2023-10-23 20:03:02

Go缓存

2019-12-12 13:50:27

strace追踪系统调用Linux

2023-05-24 16:41:41

React前端

2021-01-05 08:39:51

容器前端流水线

2021-02-20 09:14:35

PythonPygal可视化

2021-09-21 15:44:02

LinuxOBSWayland

2022-01-03 08:06:15

函数Go数据

2023-03-30 07:48:46

接口鉴权SpringBoot

2022-11-03 20:38:01

CMD命令Go

2010-06-23 15:21:45

SharepointExchange

2023-12-31 16:29:31

GoGoroutinesChannels

2022-05-17 08:25:10

TypeScript接口前端

2009-06-08 20:04:06

EclipseJUnit4单元测试

2021-03-17 11:21:06

React数据存储
点赞
收藏

51CTO技术栈公众号