禁用緩存將壓倒你的網絡攝像頭(甚至是好的),如果它被越來越多的
我試圖讓圖像被緩存6秒(Cache-Control:max-age = 6),因爲我需要防止網絡攝像頭被淹沒。我是有工作的代碼看起來有點像這樣,但它有一個問題:
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg';
}, 6000);
}());
</script>
此前,網絡開發已經把一個蘭特=(隨機數)作爲一個緩存阻止技術? 。如果圖像緩存(即使只有很短的時間),這很糟糕,因爲如果意味着您可能(取決於您的緩存是否將查詢參數視爲不可緩存),意味着您的緩存命中率非常低你會得到很多頁面表示正在建立。
問題是,圖像現在不刷新,因爲雖然src屬性被重新分配,但實際上並沒有改變爲不同的值,所以瀏覽器(Chrome 51)沒有更新圖像。我將邏輯改爲具有?1
或?2
查詢字符串參數,並在它們之間交替。
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg?1" /><br />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
if (myImageElement.src == 'http://example.com/webcams/suddenlypopular.jpg?1') {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?2';
} else {
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?1';
}
myLogElement.innerHTML = myImageElement.src;
}, 6000);
}());
</script>
編輯:雖然這部作品在Chrome和IE瀏覽器,它不工作在Firefox,所以我想出了是在Chrome,Firefox和IE工作的替代解決方案(Safari瀏覽器目前是未經測試) 。
<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" />
<script type="text/javascript">
(function() {
setInterval(function() {
var myImageElement = document.getElementById('liveimage');
var d = new Date();
// 6000 is 6 seconds; the desired refresh rate
// % n is a bit of an experiment for being nice on cache invalidation; it also puts a bound on how out-of-date something would be regarding clock skew.
var timeSlice = Math.floor(d.getTime()/6000) % 3;
myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?t=' + timeSlice;
}, 6000);
}());
</script>
所以,現在我有一個緩存友好的攝像頭,不更新。
Apache的反向代理配置
下面是來自Apache的httpd的片段你會如何反向代理一個網絡攝像頭設置一個特定的緩存策略。
<Location /webcams/suddenlypopular.jpg>
ProxyPass http://mywebcamdevice.example.com/snapshot.jpg
ProxyPassReverse http://mywebcamdevice.example.com/snapshot.jpg
ExpiresByType image/jpeg "access plus 6 seconds"
Header unset ETag
Header unset Last-Modified
</Location>
你的信息很棒,你確實做了一些禮儀,事實上你不只是給了我答案。雖然我確實很快瀏覽了其他答案,但是一旦我閱讀了你的文章並自己寫下了其他答案,我就不再這麼做了。謝謝你提醒我。從現在起,我將不得不聲明,我不只是想要一個明目張膽的答案,謝謝! – zillaofthegods 2011-05-04 13:01:44
@ghostcake - 愉悅:) – 2011-05-04 13:32:20
如果它受歡迎,這將壓倒一個攝像頭。最好設置一個小的緩存控制最大年齡(如6秒),並將更多的緩存作爲查詢字符串(只是爲了說服瀏覽器URL已更改)請參閱下面的答案以獲取更多信息。 – 2016-06-24 11:21:19