- making multiple identical requests has the same effect as making a single request
【相同请求会和一条请求效果一样】
实现方案(列举3种)
- Database transactions 数据库事务
每个事务记个unique ID,操作前检查ID是否重复,重复就不执行。 - Tokens 这玩意调用别人API时经常用
每次请求按唯一防重token区分。unique “deduplication token” 。
【payment processing systems支付系统极其常用,避免重复支付!!】 - function logic 业务逻辑中
把结果储存在缓存中。当被调用时,首先检查结果是否已知,有则直接取缓存返回。
若缓存里没有再去查/做业务操作。
storing the results of previous invocations in a cache. When the function is called, first check the cache to see if the result for that input is already known. If it is, return the cached result. If not, perform the calculation and store the result in the cache before returning it.
type Cache struct {
sync.Mutex
data map[int]int
}
var cache = Cache{
data: make(map[int]int),
}
func heavyComputation(input int) int {
// 首先缓存锁住 Lock the cache while we're using it
cache.Lock()
defer cache.Unlock()
// 查看是否缓存里有 Check if we have a cached result
if result, ok := cache.data[input]; ok {
return result
}
// 若缓存没有,再执行业务操作 If not, perform the operation (this is just a stand-in for a more complex operation)
result := input * input
// Store the result in the cache
cache.data[input] = result
return result
}