Set Cache Expiration

Set cache expiration?

Following the Yahoo! Best Practices for Speeding Up Your Web Site,
you should Add an Expires or a Cache-Control Header and Configure ETags.

How you actually go about configuring the server to do this depends on far more information than you have provided in the question.

Do I have to set cache expiration every time on HTML?

The tag has limited effect. In particular, it does not affect proxies, since they work on HTTP headers and do not parse HTML documents.

After the expiry time, browsers are expected to treat the copy of the page in their caches as stale and not use it but request for the page from the server (if online), at least conditionally (send if modified since such-and-such). This means that after any new request for the page, the copy received should not be cached at all. So yes, you should set a new expiry date, unless you really want to prevent caching.

The Expires header or its meta simulation needs to have a specific time mentioned. There are other ways to affect caches, see http://www.mnot.net/cache_docs/

How do i set caches expiration time through javascript using service worker or cache object

Before sending a cached file to client, You can check when file have been fetch and if it's too old, fetch a new one :

const url = request.url;
caches.open(cacheName).then(cache => {
cache.match(url).then(response => {
if(!response) {
return fetch(url);
}

const date = new Date(response.headers.get('date'))
// if cached file is older than 6 hours
if(Date.now() > date.getTime() + 1000 * 60 * 60 * 6){
return fetch(url);
}

// else return cached version
return response;
})
})

Caffeine Cache - Specify expiry for an entry

This can be done by using a custom expiration policy and leverage an unreachable duration. The maximum duration is Long.MAX_VALUE, which is 292 years in nanoseconds. Assuming your record holds when (and if) it expires then you might configure the cache as,

LoadingCache<Key, Graph> graphs = Caffeine.newBuilder()
.expireAfter(new Expiry<Key, Graph>() {
public long expireAfterCreate(Key key, Graph graph, long currentTime) {
if (graph.getExpiresOn() == null) {
return Long.MAX_VALUE;
}
long seconds = graph.getExpiresOn()
.minus(System.currentTimeMillis(), MILLIS)
.toEpochSecond();
return TimeUnit.SECONDS.toNanos(seconds);
}
public long expireAfterUpdate(Key key, Graph graph,
long currentTime, long currentDuration) {
return currentDuration;
}
public long expireAfterRead(Key key, Graph graph,
long currentTime, long currentDuration) {
return currentDuration;
}
})
.build(key -> createExpensiveGraph(key));

How to set NSURLRequest cache expiration?

So, I found the solution.

The idea is to use connection:willCacheResponse: method. Before cache the response it will be executed and there we can change response and return new, or return nil and the response will not be cached. As I use AFNetworking, there is a nice method in operation:

- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block;

Add code:

  [operation setCacheResponseBlock:^NSCachedURLResponse *(NSURLConnection *connection, NSCachedURLResponse *cachedResponse) {
if([connection currentRequest].cachePolicy == NSURLRequestUseProtocolCachePolicy) {
cachedResponse = [cachedResponse responseWithExpirationDuration:60];
}
return cachedResponse;
}];

Where responseWithExpirationDuration from category:

@interface NSCachedURLResponse (Expiration)
-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration;
@end

@implementation NSCachedURLResponse (Expiration)

-(NSCachedURLResponse*)responseWithExpirationDuration:(int)duration {
NSCachedURLResponse* cachedResponse = self;
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)[cachedResponse response];
NSDictionary *headers = [httpResponse allHeaderFields];
NSMutableDictionary* newHeaders = [headers mutableCopy];

newHeaders[@"Cache-Control"] = [NSString stringWithFormat:@"max-age=%i", duration];
[newHeaders removeObjectForKey:@"Expires"];
[newHeaders removeObjectForKey:@"s-maxage"];

NSHTTPURLResponse* newResponse = [[NSHTTPURLResponse alloc] initWithURL:httpResponse.URL
statusCode:httpResponse.statusCode
HTTPVersion:@"HTTP/1.1"
headerFields:newHeaders];

cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:newResponse
data:[cachedResponse.data mutableCopy]
userInfo:newHeaders
storagePolicy:cachedResponse.storagePolicy];
return cachedResponse;
}

@end

So, we set expiration in seconds in http header according to http/1.1
For that we need one of headers to be set up:
Expires, Cache-Control: s-maxage or max-age
Then create new cache response, because the properties is read only, and return new object.

Cache expires although explicitly set not to expire

Chances are if you are leaving it for some time then your app domain is shutting down due to lack of use and if that goes so does its in memory cache.

ASP.NET Data Cache - preserve contents after app domain restart discusses this issue and some possible solutions to it.



Related Topics



Leave a reply



Submit