设计思路
- 数据结构选择:使用Go语言的
map
作为基础数据结构来存储键值对。
- 并发安全处理:为了处理高并发读写,使用
sync.RWMutex
来保证线程安全。读操作使用读锁(RLock
),写操作(添加、删除)使用写锁(Lock
)。
代码实现
package main
import (
"fmt"
"sync"
)
type Cache struct {
data map[string]interface{}
mutex sync.RWMutex
}
// 添加数据
func (c *Cache) Set(key string, value interface{}) {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.data == nil {
c.data = make(map[string]interface{})
}
c.data[key] = value
}
// 获取数据
func (c *Cache) Get(key string) (interface{}, bool) {
c.mutex.RLock()
defer c.mutex.RUnlock()
if c.data == nil {
return nil, false
}
value, exists := c.data[key]
return value, exists
}
// 删除数据
func (c *Cache) Delete(key string) {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.data == nil {
return
}
delete(c.data, key)
}
使用示例
func main() {
cache := Cache{}
cache.Set("key1", "value1")
value, exists := cache.Get("key1")
if exists {
fmt.Printf("Get key1: %v\n", value)
}
cache.Delete("key1")
value, exists = cache.Get("key1")
if exists {
fmt.Printf("Get key1: %v\n", value)
} else {
fmt.Println("key1 not exists")
}
}
解释
- Cache结构体:包含一个
map
用于存储键值对,以及一个sync.RWMutex
用于处理并发安全。
- Set方法:使用写锁保证在添加数据时的线程安全。如果
map
还未初始化,则先进行初始化。
- Get方法:使用读锁保证在读取数据时的线程安全。如果
map
未初始化,直接返回空值和false
。
- Delete方法:使用写锁保证在删除数据时的线程安全。如果
map
未初始化,直接返回。