Skip to content

Instantly share code, notes, and snippets.

@nuboat
Created June 4, 2015 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuboat/34a9ceb3c368198c97c1 to your computer and use it in GitHub Desktop.
Save nuboat/34a9ceb3c368198c97c1 to your computer and use it in GitHub Desktop.
Cache with AOP
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;
}
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)
}
}
}
...
@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