I use cookies for page cache, is that okay?
To show partially static contents( updated very rarel开发者_运维问答y from database), i don't like to interact much with database so can i use cookie to store that results in client's computer and display data directly from it?
For data authenticity and integrity, i created a crc for data and stored along with data in that cookie. THe algorithm of crc calculation is hardcoded(assume), so
Does the idea has any demerits?
Cookies should not be used for caching, since your cookie is sent from the browser to the server on each request!! This means you send more bytes, which means higher latency. So you are actually slowing your system down, not helping it, by using cookies in this way. The proper way to cache data on a website is to use localStorage
(or one of the other HTML5 storage classes) to cache it.
This sounds like a bad idea to me. Is the cached data user-specific or global? For global data you'd be much better off caching the entire generated page on the server side and responding with that for future requests. Using cookies you'd still need to dynamically generate a page on each request.
For user-specific data, it depends on the page, but you generally want to store thing like a user's name in the session. Caching something like a user's profile page won't be very helpful since it doesn't get hit very often.
In either case, you're going to end up wasting a lot of bandwidth receiving all that extra information on each request and you still have to dynamically generate a page for every request. There are also security implications if your checksum algorithm is compromised and you store anything important in the cookie like an account balance or even a username. Further, how do you invalidate the data cached in the cookie? There would need to be a mechanism on every request to check if the data is old, which defeats the purpose.
Cookies should be used to store small strings like session ids and usernames.
You're better off writing the static content to a local file on your server (or to a database) and serving the static content until you decide to expire it - then repeating that process.
There are servers, such as memcached, which are very efficient at doing this but the psuedocode is the same:
if (is_cached('recent_articles') {
return cached_content('recent_articles');
else {
save('recent_articles', $articles)
return cached_content('recent_articles')
}
Just make sure to expire content after a certain amount of time or when you know its stale - whichever makes the most sense.
精彩评论