Skip to content
This repository has been archived by the owner on Jan 30, 2021. It is now read-only.

Commit

Permalink
Allow customization of @CacheFor cache key playframework#1133
Browse files Browse the repository at this point in the history
  • Loading branch information
tahseenarticle committed Jun 19, 2017
1 parent 5e564b5 commit 811a235
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
1 change: 1 addition & 0 deletions framework/src/play/cache/CacheFor.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@
public @interface CacheFor {
String value() default "1h";
String id() default "";
Class<? extends CacheKeyGenerator> generator() default DefaultCacheKeyGenerator.class;
}
10 changes: 10 additions & 0 deletions framework/src/play/cache/CacheKeyGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package play.cache;

import play.mvc.Http.Request;

/**
* Allow custom cache key to be used by applications.
*/
public interface CacheKeyGenerator {
public String generate(Request request);
}
13 changes: 13 additions & 0 deletions framework/src/play/cache/DefaultCacheKeyGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package play.cache;

import play.mvc.Http.Request;

/**
* The Default Cache Key Generator
*/
public class DefaultCacheKeyGenerator implements CacheKeyGenerator {
@Override
public String generate(Request request) {
return "urlcache:" + request.url + request.querystring;
}
}
12 changes: 8 additions & 4 deletions framework/src/play/mvc/ActionInvoker.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,15 @@ public static void invoke(Http.Request request, Http.Response response) {

// Check the cache (only for GET or HEAD)
if ((request.method.equals("GET") || request.method.equals("HEAD")) && actionMethod.isAnnotationPresent(CacheFor.class)) {
cacheKey = actionMethod.getAnnotation(CacheFor.class).id();
CacheFor cacheFor = actionMethod.getAnnotation(CacheFor.class);;
cacheKey = cacheFor.id();
if ("".equals(cacheKey)) {
cacheKey = "urlcache:" + request.url + request.querystring;
// Generate a cache key for this request
cacheKey = cacheFor.generator().newInstance().generate(request);
}
if(cacheKey != null && !"".equals(cacheKey)) {
actionResult = (Result) Cache.get(cacheKey);
}
actionResult = (Result) Cache.get(cacheKey);
}

if (actionResult == null) {
Expand All @@ -161,7 +165,7 @@ public static void invoke(Http.Request request, Http.Response response) {
} catch (Result result) {
actionResult = result;
// Cache it if needed
if (cacheKey != null) {
if (cacheKey != null && !"".equals(cacheKey)) {
Cache.set(cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
}
} catch (JavaExecutionException e) {
Expand Down

0 comments on commit 811a235

Please sign in to comment.