Golang 实现本地持久化缓存

// Copyright (c) 2024 LiuShuKu
// Project Name : balance
// Author : liushuku@yeah.net

package cache

import (
	"encoding/json"
	"log"
	"os"
	"strconv"
	"sync"
)

// Cache 结构体定义
type Cache struct {
	data      map[string]string
	mutex     sync.RWMutex
	file      string
	dirtyFlag bool // 标记数据是否已更改
}

// NewCache 创建新的 Cache 实例
func NewCache(file string) *Cache {
	cache := &Cache{
		data: make(map[string]string),
		file: file,
	}
	if err := cache.load(); err != nil {
		log.Printf("加载缓存时出错: %v", err)
	}
	return cache
}

// Get 从缓存中获取值
func (c *Cache) Get(key string) string {
	c.mutex.RLock()
	defer c.mutex.RUnlock()
	value, _ := c.data[key]
	return value
}

// Increment 自增接口
func (c *Cache) Increment(key string) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	currentValue, found := c.data[key]
	var newValue int
	if found {
		currentInt, err := strconv.Atoi(currentValue)
		if err != nil {
			newValue = 1
		} else {
			newValue = currentInt + 1
		}
	} else {
		newValue = 1
	}
	c.data[key] = strconv.Itoa(newValue)
	c.dirtyFlag = true // 标记数据已更改
	c.saveIfDirty()
}

// Set 将值存入缓存
func (c *Cache) Set(key, value string) {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	if c.data[key] != value {
		c.data[key] = value
		c.dirtyFlag = true // 标记数据已更改
	}
	c.saveIfDirty()
}

// Save 持久化缓存到文件
func (c *Cache) save() error {
	fileData, err := json.MarshalIndent(c.data, "", " ")
	if err != nil {
		log.Printf("序列化数据时出错: %v", err)
		return err
	}
	if err := os.WriteFile(c.file, fileData, 0644); err != nil {
		log.Printf("写入文件时出错: %v", err)
		return err
	}
	return nil
}

// Load 从文件加载缓存
func (c *Cache) load() error {
	fileData, err := os.ReadFile(c.file)
	if err != nil {
		if !os.IsNotExist(err) {
			log.Printf("读取文件时出错: %v", err)
		}
		return err
	}
	if err := json.Unmarshal(fileData, &c.data); err != nil {
		log.Printf("解析 JSON 时出错: %v", err)
		return err
	}
	return nil
}

// saveIfDirty 如果数据已更改,则保存到文件
func (c *Cache) saveIfDirty() {
	if c.dirtyFlag {
		if err := c.save(); err == nil {
			c.dirtyFlag = false // 保存成功后重置脏标记
		}
	}
}

posted @ 2024-11-06 17:26  LiuShuku  阅读(134)  评论(0)    收藏  举报