{"id":207000,"date":"2025-07-08T09:52:56","date_gmt":"2025-07-08T01:52:56","guid":{"rendered":"https:\/\/server.hk\/cnblog\/207000\/"},"modified":"2025-07-08T09:52:56","modified_gmt":"2025-07-08T01:52:56","slug":"%e5%a6%82%e4%bd%95%e5%90%8c%e6%ad%a5%e6%85%a2%e9%80%9f%e8%ae%a1%e7%ae%97%e5%b9%b6%e7%bc%93%e5%ad%98%e5%ae%83%ef%bc%9f","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/207000\/","title":{"rendered":"\u5982\u4f55\u540c\u6b65\u6162\u901f\u8ba1\u7b97\u5e76\u7f13\u5b58\u5b83\uff1f"},"content":{"rendered":"<p><b><\/b> <\/p>\n<p>\u5f53\u524d\u4f4d\u7f6e\uff1a <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>&gt;<\/span> <span>\u5982\u4f55\u540c\u6b65\u6162\u901f\u8ba1\u7b97\u5e76\u7f13\u5b58\u5b83\uff1f<\/span><\/p>\n<p><span>\u6765\u6e90\uff1astackoverflow<\/span><br \/>\n<span>2024-04-19 13:18:33<\/span><br \/>\n<span><i><\/i>0\u6d4f\u89c8<\/span><br \/>\n<span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span> <\/p>\n<p>\u4eca\u5929\u7ed9\u5927\u5bb6\u5e26\u6765\u4e86<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300a\u5982\u4f55\u540c\u6b65\u6162\u901f\u8ba1\u7b97\u5e76\u7f13\u5b58\u5b83\uff1f\u300b<\/span>\uff0c\u5176\u4e2d\u6d89\u53ca\u5230\u7684\u77e5\u8bc6\u70b9\u5305\u62ec<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\u7b49\u7b49\uff0c\u65e0\u8bba\u4f60\u662f\u5c0f\u767d\u8fd8\u662f\u8001\u624b\uff0c\u90fd\u9002\u5408\u770b\u4e00\u770b\u54e6~\u6709\u597d\u7684\u5efa\u8bae\u4e5f\u6b22\u8fce\u5927\u5bb6\u5728\u8bc4\u8bba\u7559\u8a00\uff0c\u82e5\u662f\u770b\u5b8c\u6709\u6240\u6536\u83b7\uff0c\u4e5f\u5e0c\u671b\u5927\u5bb6\u80fd\u591a\u591a\u70b9\u8d5e\u652f\u6301\u5440\uff01\u4e00\u8d77\u52a0\u6cb9\u5b66\u4e60~<\/p>\n<p> \u95ee\u9898\u5185\u5bb9<br \/>\n <\/p>\n<p>\u5728 golang \u540e\u7aef\u4e2d\uff0c\u6211\u60f3\u4e3a\u591a\u4e2a\u5ba2\u6237\u7aef\u63d0\u4f9b\u4e00\u4e2a\u503c\uff0c\u6211\u4eec\u79f0\u4e4b\u4e3a\u5206\u6570\u3002\u5206\u6570\u968f\u65f6\u95f4\u53d8\u5316\uff0c\u5176\u8ba1\u7b97\u901f\u5ea6\u8f83\u6162\u3002\u8ba1\u7b97\u4e0d\u4f9d\u8d56\u4e8e\u5148\u524d\u7684\u7ed3\u679c\u3002\u5f53\u6ca1\u6709\u5ba2\u6237\u65f6\u6211\u6839\u672c\u4e0d\u60f3\u8ba1\u7b97\u5b83\u3002\u56e0\u6b64\uff0c\u8ba1\u7b97\u5e94\u8be5\u4ec5\u6839\u636e\u8bf7\u6c42\u8fdb\u884c\u3002\u4f46\u8fd8\u6709\u4e00\u4e2a\u4e8b\u5b9e\u2014\u2014\u5206\u6570\u5728 5 \u79d2\u5185\u4e0d\u80fd\u6539\u53d8\u3002\u6240\u4ee5\u6211\u5c1d\u8bd5\u4e86\u4e0d\u540c\u7684\u65b9\u6cd5\uff0c\u4f46\u4e00\u5207\u90fd\u6709\u5176\u7f3a\u70b9\uff1a<\/p>\n<ol>\n<li>\u5728\u6ca1\u6709\u5ba2\u6237\u7684\u60c5\u51b5\u4e0b\u8fdb\u884c\u6602\u8d35\u7684\u8ba1\u7b97\uff1a<\/li>\n<\/ol>\n<pre>var score interface{}\n\n\/\/ run in a separate goroutine\nfunc calculatescoreperiodically() {\n    for{\n        select{\n        case &lt;-time.after(5*time.second):\n            score = calculatescoreexpensiveandslow()\n        }\n    }\n}\n\nfunc servescore(w http.responsewriter, r* http.request) {\n    b, _ := json.marshal(score)\n    w.write(b)\n}<\/pre>\n<ol>\n<li>\u5728\u5f88\u957f\u7684\u8ba1\u7b97\u65f6\u95f4\u5185\u963b\u6b62\u6240\u6709\u5ba2\u6237\u7aef\uff08\u4f46\u5b9e\u9645\u4e0a\u53ef\u80fd\u53ea\u662f\u5411\u4ed6\u4eec\u63d0\u4f9b\u65e7\u6570\u636e\uff09\u3002\u5e76\u4e14\u60a8\u4e0d\u80fd\u5c06 <code>if<\/code> \u79fb\u51fa\u4e92\u65a5\u4f53\uff0c\u56e0\u4e3a\u8fd9\u6837\u591a\u4e2a\u5ba2\u6237\u7aef\u53ef\u80fd\u4f1a\u540c\u65f6\u8fdb\u5165\u8ba1\u7b97\u5757\uff0c\u5e76\u4e14\u4e0d\u4f1a\u5728 5 \u79d2\u95f4\u9694\u5185\u8fdb\u884c\u8ba1\u7b97\uff0c\u800c\u662f\u6309\u987a\u5e8f\u8fdb\u884c\u8ba1\u7b97\uff1a<\/li>\n<\/ol>\n<pre>var (\n    score interface{}\n    mutex sync.Mutex\n    updatedAt time.Time\n)\n\nfunc getCachedScore() float64 {\n    mutex.Lock()\n    defer mutex.Unlock()\n    currentTime := time.Now()\n    if currentTime.Sub(updatedAt) &lt; 5*time.Second {\n        return score\n    }\n    updatedAt = currentTime\n    score = calculateScoreExpensiveAndSlow()\n    return score\n}\n\nfunc serveScore(w http.ResponseWriter, r* http.Request) {\n    b, _ := json.Marshal(getCachedScore())\n    w.Write(b)\n}<\/pre>\n<p>\u5982\u4f55\u89e3\u51b3\u4ee5\u4e0a\u4e24\u4e2a\u7f3a\u70b9\uff1f<\/p>\n<p> ps\u3002\u6211\u8ba4\u4e3a\u8fd9\u662f\u4e00\u4e2a\u666e\u904d\u95ee\u9898\uff0c\u4e5f\u662f\u4e00\u4e2a\u6a21\u5f0f &#8211; \u5b83\u6709\u4e00\u4e2a\u7279\u6b8a\u7684\u540d\u79f0\u5417\uff1f<br \/>\n <\/p>\n<h2>\u6b63\u786e\u7b54\u6848<\/h2>\n<p> <\/p>\n<p>\u53ef\u80fd\u6709\u591a\u79cd\u89e3\u51b3\u65b9\u6848\u3002\u4e00\u4e2a\u7b80\u5355\u7684\u89e3\u51b3\u65b9\u6848\u662f\u6307\u5b9a\u4e00\u4e2a goroutine \u8fdb\u884c\u8ba1\u7b97\uff0c\u60a8\u53ef\u4ee5\u901a\u8fc7\u5728\u901a\u9053\u4e0a\u53d1\u9001\u503c\u6765\u5411\u5176\u53d1\u51fa\u9700\u8981\u91cd\u65b0\u8ba1\u7b97\u7684\u4fe1\u53f7\u3002\u53d1\u9001\u53ef\u80fd\u662f\u975e\u963b\u585e\u7684\uff0c\u56e0\u6b64\u5982\u679c\u6b63\u5728\u8fdb\u884c\u8ba1\u7b97\uff0c\u5219\u4e0d\u4f1a\u53d1\u751f\u4efb\u4f55\u4e8b\u60c5\u3002<\/p>\n<p>\u8fd9\u662f\u4e00\u4e2a\u53ef\u91cd\u7528\u7684\u7f13\u5b58\u5b9e\u73b0\uff1a<\/p>\n<pre>type cache struct {\n    mu      sync.rwmutex\n    value   interface{}\n    updated time.time\n\n    calcch     chan struct{}\n    expiration time.duration\n}\n\nfunc newcache(calc func() interface{}, expiration time.duration) *cache {\n    c := &amp;cache{\n        value:   calc(),\n        updated: time.now(),\n        calcch:  make(chan struct{}),\n    }\n\n    go func() {\n        for range c.calcch {\n            v := calc()\n\n            c.mu.lock()\n            c.value, c.updated = v, time.now()\n            c.mu.unlock()\n        }\n    }()\n\n    return c\n}\n\nfunc (c *cache) get() (value interface{}, updated time.time) {\n    c.mu.rlock()\n    value, updated = c.value, c.updated\n    c.mu.runlock()\n\n    if time.since(updated) &gt; c.expiration {\n        \/\/ trigger a new calculation (will happen in another goroutine).\n        \/\/ do non-blocking send, if a calculation is in progress,\n        \/\/ this will have no effect\n        select {\n        case c.calcch &lt;- struct{}{}:\n        default:\n        }\n    }\n\n    return\n}\n\nfunc (c *cache) stop() {\n    close(c.calcch)\n}<\/pre>\n<p>\u6ce8\u610f\uff1a<code>cache.stop()<\/code>\u662f\u505c\u6b62\u540e\u53f0goroutine\u3002\u8c03\u7528<code>cache.stop()<\/code>\u540e\uff0c\u4e0d\u5f97\u518d\u8c03\u7528<code>cache.get()<\/code>\u3002<\/p>\n<p>\u5c06\u5176\u7528\u4e8e\u60a8\u7684\u6848\u4f8b\uff1a<\/p>\n<pre>func getcachedscore() interface{} {\n    \/\/ ...\n}\n\nvar scorecache = newcache(getcachedscore, 5*time.second)\n\nfunc servescore(w http.responsewriter, r* http.request) {\n    score, _ := scorecache.get()\n    b, _ := json.marshal(score)\n    w.write(b)\n}<\/pre>\n<p>\u8fd9\u662f\u6211\u5b9e\u73b0\u7684\uff0c\u4e0e icza \u7684\u7b54\u6848\u76f8\u5173\uff0c\u4f46\u8fd8\u6709\u66f4\u591a\u529f\u80fd\uff1a<\/p>\n<pre>package common\n\nimport (\n    \"context\"\n    \"sync\/atomic\"\n    \"time\"\n)\n\ntype (\n    CachedUpdater func() interface{}\n    ChanStruct    chan struct{}\n)\n\ntype Cached struct {\n    value        atomic.Value  \/\/ holds the cached value's interface{}\n    updatedAt    atomic.Value  \/\/ holds time.Time, time when last update sequence was started at\n    updatePeriod time.Duration \/\/ controls minimal anount of time between updates\n    needUpdate   ChanStruct\n}\n\n\/\/cachedUpdater is a user-provided function with long expensive calculation, that gets current state\nfunc MakeCached(ctx context.Context, updatePeriod time.Duration, cachedUpdater CachedUpdater) *Cached {\n    v := &amp;Cached{\n        updatePeriod: updatePeriod,\n        needUpdate:   make(ChanStruct),\n    }\n    \/\/v.updatedAt.Store(time.Time{}) \/\/ \"was never updated\", but time should never be nil interface\n    v.doUpdate(time.Now(), cachedUpdater)\n    go v.updaterController(ctx, cachedUpdater)\n    return v\n}\n\n\/\/client will get cached value immediately, and optionally may trigger an update, if value is outdated\nfunc (v *Cached) Get() interface{} {\n    if v.IsExpired(time.Now()) {\n        v.RequestUpdate()\n    }\n    return v.value.Load()\n}\n\n\/\/updateController goroutine can be terminated both by cancelling context, provided to maker, or by closing chan\nfunc (v *Cached) Stop() {\n    close(v.needUpdate)\n}\n\n\/\/returns true if value is outdated and updater function was likely not called yet\nfunc (v *Cached) IsExpired(currentTime time.Time) bool {\n    updatedAt := v.updatedAt.Load().(time.Time)\n    return currentTime.Sub(updatedAt) &gt; v.updatePeriod\n}\n\n\/\/requests updaterController to perform update, using non-blocking send to unbuffered chan. controller can decide not to update in case if it has recently updated value\nfunc (v *Cached) RequestUpdate() bool {\n    select {\n    case v.needUpdate &lt;- struct{}{}:\n        return true\n    default:\n        return false\n    }\n}\n\nfunc (v *Cached) updaterController(ctx context.Context, cachedUpdater CachedUpdater) {\n    for {\n        select {\n        case &lt;-ctx.Done():\n            return\n        case _, ok := &lt;-v.needUpdate:\n            if !ok {\n                return\n            }\n            currentTime := time.Now()\n            if !v.IsExpired(currentTime) {\n                continue\n            }\n            v.doUpdate(currentTime, cachedUpdater)\n        }\n    }\n}\n\nfunc (v *Cached) doUpdate(currentTime time.Time, cachedUpdater CachedUpdater) {\n    v.updatedAt.Store(currentTime)\n    v.value.Store(cachedUpdater())\n}<\/pre>\n<p>\u4eca\u5929\u5173\u4e8e\u300a\u5982\u4f55\u540c\u6b65\u6162\u901f\u8ba1\u7b97\u5e76\u7f13\u5b58\u5b83\uff1f\u300b\u7684\u5185\u5bb9\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\uff0c\u5982\u679c\u6709\u4ec0\u4e48\u7591\u95ee\u6216\u8005\u5efa\u8bae\uff0c\u53ef\u4ee5\u5728\u516c\u4f17\u53f7\u4e0b\u591a\u591a\u56de\u590d\u4ea4\u6d41\uff1b\u6587\u4e2d\u82e5\u6709\u4e0d\u6b63\u4e4b\u5904\uff0c\u4e5f\u5e0c\u671b\u56de\u590d\u7559\u8a00\u4ee5\u544a\u77e5\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f53\u524d\u4f4d\u7f6e\uff1a &gt; &gt; &#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-207000","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207000","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=207000"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/207000\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=207000"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=207000"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=207000"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}