我正在研究一个使用jersey来映射资源的maven-jetty-plugin。如何将版本号缓存5个小时,以便每次页面加载时都不必获取它?
这是html代码,一旦加载就会包含版本号:
...
<footer>
<hr/>
VERSION: <span id="version-container">...Loading...</span>
</footer>
这是web.xml,其servlet映射到'localhost:8080 / rest /':
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
以下是在'localhost:8080 / rest / version'处理GET的java代码:
/* ... package & imports omitted ... */
@Path("/")
public class RootResource {
@GET
@Path("/version")
@Produces(MediaType.APPLICATION_JSON)
public String versionAsJson(){
return String.format("{ \"version\": \"%s\"}", "v.01");
}
}
这是在页面加载后加载版本的javascript代码(使用jQuery):
$(document).ready(function() {
$.get("http://localhost:8080/rest/version",
function(response){
$("#version-container").html(response.version);
},
"json"
).error(function(){
$("#version-container").html("[FAILED TO GET VERSION]");
});
}
答案 0 :(得分:0)
Guava库具有非常好的缓存支持:
@Path("/")
public class Service {
protected LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(5L, TimeUnit.HOURS).maximumSize(1L)
.build(new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
return String.format("{ \"version\": \"%s\"}", "v.01");
}
});
@GET
@Path("/version")
@Produces(MediaType.APPLICATION_JSON)
public String run() throws ExecutionException {
return cache.get("version");
}
}