Created
June 4, 2015 02:55
-
-
Save nuboat/34a9ceb3c368198c97c1 to your computer and use it in GitHub Desktop.
Cache with AOP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package intercept; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.METHOD) | |
public @interface LocalCache { | |
public String key(); | |
public int timeout() default 3600; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package intercept | |
import java.util.concurrent.TimeUnit | |
import com.google.common.base.Stopwatch | |
import models.GroupJobLevel | |
import org.aopalliance.intercept.{MethodInterceptor, MethodInvocation} | |
import play.api.Logger | |
import play.api.cache.Cache | |
import play.api.Play.current | |
private class LocalCacheInterceptor extends MethodInterceptor { | |
val log = Logger("profiler") | |
def invoke(invocation: MethodInvocation): AnyRef = { | |
val watch = Stopwatch.createStarted() | |
val annotated = invocation.getMethod.getAnnotation(classOf[LocalCache]) | |
val key = annotated.key() | |
val timeout = annotated.timeout() | |
try { | |
val cache = Cache.get(key) | |
if (cache.isDefined) { | |
return cache.get.asInstanceOf[AnyRef] | |
} | |
val any = invocation.proceed() | |
Cache.set(key, any, timeout) | |
return any | |
} finally { | |
val elapsed = watch.stop.elapsed(TimeUnit.MILLISECONDS) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
@Profiler | |
@LocalCache(key = "GROUPJOBLEVEL") | |
def groupJobLevel(): List[GroupJobLevel] = { | |
return queryGroupJobLevel() | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment