首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java网站下载缓存API

Java网站下载缓存API
EN

Stack Overflow用户
提问于 2011-10-04 18:59:09
回答 2查看 209关注 0票数 0

我在我的java应用程序中使用了2个模块来下载相同的网页。因此,该网站实际上被下载了两次。为了避免这种情况,是否有一些缓存层,我可以附加,以便只有一个副本的网站实际下载。

我很乐意看到Java端的缓存,如果不可能在以后的级别,如一些web缓存代理或其他

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-04 19:13:38

如果这两个“模块”在同一个jvm中,因此可以访问彼此的内存,那么可以尝试基于单例的“缓存”。我倾向于使用HtmlSnippit缓存来缓存大量重复的HTML片段,并取得了巨大的成功:

代码语言:javascript
复制
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的,但这是另一个讨论(论点?)总而言之:)

(示例应该开箱即用。)

票数 0
EN

Stack Overflow用户

发布于 2011-10-04 19:28:40

这可能有点离题,因为这个解决方案使用了spring:

您可以使用ehcache-spring-annotations来进行缓存,而无需编写任何代码。

实际上,您需要在ehcache.xml中定义一个缓存:

代码语言:javascript
复制
<ehcache>
    ...
    <cache 
       name="htmlCache" 
       maxElementsInMemory="10" 
       eternal="true" 
       overflowToDisk="false" />
</ehcache>

配置为在spring应用程序上下文中使用缓存注释:

代码语言:javascript
复制
<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>

并注释您的代码以自动缓存:

代码语言:javascript
复制
@Cacheable(cacheName = "htmlCache")
public String getHtml(String url) {
    ...
}

这将根据其参数(url)缓存getHtml方法的结果,因此当使用相同的url第二次调用该方法时,结果将直接来自缓存。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7646835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档