golang localcache 小工具

194 阅读1分钟

前言

在项目开发中我们经常用缓存,缓存分为本地缓存、远程缓存。

本地缓存指的缓存本地服务器上的缓存,远程缓存一般指的是redis等缓存工具。

本地缓存优势不需要引入第三方工具,直接将数据写入文件或者内存中,确定是如果分布式部署的化,缓存无法共享,可能会出现数据跳动现象。

内容

本人用golang写了个本地缓存工具,给大家分享下。

缓存业务数据

package main

import (
   "fmt"
   "github.com/codewangz/goutils/cache"
   "time"
)

func main() {
   cache := cache.NewLocalCaches()
   cache.Set("a", "abed", 60*time.Second)                              //缓存普通类型60秒,默认指的时间为3分分钟
   cache.Set("b", map[string]interface{}{"a": "1111"}, 60*time.Second) //缓存map类型60秒
   fmt.Println(cache.Get("a"))
   fmt.Println(cache.Get("b"))

   s := new(student)
   //fmt.Println(s.Say())
   a := cache.CallCache(s, "Say", 60*time.Second) //缓存对象方法缓存值
   fmt.Println(a)
   b := cache.CallCache(s, "Say", 60*time.Second) //缓存对象方法缓存值
   fmt.Println(b)
   c := cache.CallCache(s, "Name", 60*time.Second, "wang") //缓存对象方法缓存值,带参数
   fmt.Println(c)
}

type student struct {
}

func (s *student) Say() string {
   fmt.Println("无缓存")
   return "hello"
}

func (s *student) Name(a string) string {
   return a
}

1、缓存简单数据,a 为key,value为"abed",时间为 60*time.Second,不传时间默认3分钟

cache.Set("a", "abed", 60*time.Second)

2、缓存方法返回值,s 为对象,"name" 为方法名,“wang”为参数。

c := cache.CallCache(s, "Name", 60*time.Second, "wang") //缓存对象方法缓存值,带参数