我在我的java应用程序中使用了2个模块来下载相同的网页。因此,该网站实际上被下载了两次。为了避免这种情况,是否有一些缓存层,我可以附加,以便只有一个副本的网站实际下载。
我很乐意看到Java端的缓存,如果不可能在以后的级别,如一些web缓存代理或其他
发布于 2011-10-04 19:13:38
如果这两个“模块”在同一个jvm中,因此可以访问彼此的内存,那么可以尝试基于单例的“缓存”。我倾向于使用HtmlSnippit缓存来缓存大量重复的HTML片段,并取得了巨大的成功:
public class Testing {
public static void main(String[] args) {
String html = "<div>The quick brown fox jumps over the lazy dog</div>";
/* Access via the getInstance() getter */
HtmlSnippitCache.getInstance().putSnippit("FOXY", html);
/* Or via local var */
HtmlSnippitCache cache = HtmlSnippitCache.getInstance();
String moreHtml = cache.getSnippit("FOXY");
System.out.println(moreHtml);
}
public static class HtmlSnippitCache {
/* Singleton implementation */
private static HtmlSnippitCache instance;
public static HtmlSnippitCache getInstance() {
if (HtmlSnippitCache.instance == null)
synchronized (HtmlSnippitCache.class) {
if (HtmlSnippitCache.instance == null)
HtmlSnippitCache.instance = new HtmlSnippitCache();
}
return HtmlSnippitCache.instance;
}
/* Ensure only local construction. */
private HtmlSnippitCache() {}
/* Clas Impl */
private HashMap<String, String> map = new HashMap<String, String>();
public boolean containsSnippit(String key) {
return map.containsKey(key);
}
public String getSnippit(String key) {
return map.get(key);
}
public String putSnippit(String key, String value) {
return map.put(key, value);
}
public int size() {
return map.size();
}
}
}现在,为了线程安全,getSnippit()和putSnippit()方法可能需要是synchronized的,但这是另一个讨论(论点?)总而言之:)
(示例应该开箱即用。)
发布于 2011-10-04 19:28:40
这可能有点离题,因为这个解决方案使用了spring:
您可以使用ehcache-spring-annotations来进行缓存,而无需编写任何代码。
实际上,您需要在ehcache.xml中定义一个缓存:
<ehcache>
...
<cache
name="htmlCache"
maxElementsInMemory="10"
eternal="true"
overflowToDisk="false" />
</ehcache>配置为在spring应用程序上下文中使用缓存注释:
<ehcache:annotation-driven />
<ehcache:config cache-manager="cacheManager"/>
<bean
id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>并注释您的代码以自动缓存:
@Cacheable(cacheName = "htmlCache")
public String getHtml(String url) {
...
}这将根据其参数(url)缓存getHtml方法的结果,因此当使用相同的url第二次调用该方法时,结果将直接来自缓存。
https://stackoverflow.com/questions/7646835
复制相似问题