go - 在 golang 中实现缓存或锁定?
问题描述
我有一个 api 需要 api_access_token 的用例......我正在考虑缓存令牌并跟踪过期时间或每个请求的锁以处理并发请求,关于如何实现或任何理想方式的任何建议?
apiAccessToken = createAPIAccessToken(ctx, userId)
url := "https://<hostname>/<api>"
c := http.Client{Timeout: time.Duration(5) * time.Second}
myJson := bytes.NewBuffer([]byte(`{"key":"set.table.attr","Custom_Field":"yes"}`))
req, err := http.NewRequest("POST", url, myJson)
if err != nil {
return
}
req.Header.Add("token", apiAccessToken)
res, err := c.Do(req)
defer res.Body.Close()
解决方案
也许这样的事情可以让你开始。这会从缓存中返回所有查询,并按计划在后台异步更新缓存time.Ticker
package main
import(
"fmt"
"time"
"sync"
)
type Cache struct {
data interface{}
update func(interface{})interface{}
l sync.Mutex
wg sync.WaitGroup
update_period time.Duration
done chan struct{}
}
func (c *Cache)Get() interface{} {
c.l.Lock()
defer c.l.Unlock()
return c.data
}
func (c *Cache)periodicUpdater() {
c.wg.Add(1)
defer c.wg.Done()
t := time.NewTicker(c.update_period)
for {
select{
case <-t.C:
fmt.Println("Updating")
newdata := c.update(c.data)
c.l.Lock()
c.data = newdata
c.l.Unlock()
case <-c.done:
t.Stop()
return
}
}
}
func main() {
c := &Cache{
update: func(data interface{}) interface{} {
if d, ok := data.(int); !ok {
panic("unexpected type")
} else {
return d+1
}
},
update_period: 1 * time.Second,
done: make(chan struct{}),
}
c.data = c.update(0)
defer c.wg.Wait()
go c.periodicUpdater()
gt := time.NewTicker(773*time.Millisecond)
for {
select {
case <-gt.C:
x := c.Get()
fmt.Println(x)
if i, ok := x.(int); !ok {
panic("how was this not an int!?!")
} else if i > 15 {
c.done <- struct{}{}
return
}
}
}
}
推荐阅读
- swift - 弹出到确切的上一个视图或动态关闭多个视图
- java - SonarQube 错误:单例类以非同步方式写入字段
- javascript - 从 localStorage 读取数据不会在反应 js 中呈现
- python - 字典中每个键出现的增量值
- flutter - Flutter:表单中的复选框及其状态
- npm - 上传后 NPM 包不会出现在 npmjs 中的搜索中
- javascript - Why does bind fix "failed to execute 'fetch' on 'Window' illegal invocation" error?
- r - 如何在闪亮的应用程序中将反应参数同步到光栅砖
- swift - 理解 getRed 输入 inout 和 inout 参数要求的问题
- moodle - Moodle 中的 JSXGraph:是否可以将 JavaScript 代码与
标签?