0

我有一个页面,它在每个“preRenderView”上填充一些带有 DB 值的列表

//preRenderView Method
public void init(){
    loadChapterStructure();
    loadCategoryStructure();
}    

由于章节和类别并不经常出现(例如,每天仅一次),因此每个用户只应加载一次(在第一页加载时)。

当用户现在在同一个视图上执行一些 GET 请求(以保持页面等可收藏)时,最好不要再次加载这些“静态”值。

有没有办法实现例如加载章节和类别,例如每小时只加载一次?这个问题有什么最佳实践吗?

谢谢你的帮助!

4

1 回答 1

0

您可以实现一个@ApplicationScoped缓存 DB 值的托管 bean。只需通过它访问数据,而不是直接使用视图 bean 中的 DAO:

@ManagedBean
@ApplicationScoped
public class CacheManager(){

    private static Date lastChapterAccess;

    private static Date lastCategoryAccess;

    private List<Chapter> cachedChapters; 

    private List<Category> cachedCategories; 

    private Dao dao;

    //Refresh the list if the last DB access happened 
    //to occur more than one hour before
    public List<Chapter> loadChapterStructure(){
        if (lastChapterAccess==null || new Date().getTime() 
            - lastChapterAccess.getTime() > 3600000){
            cachedChapters = dao.loadChapterStructure();
            lastChapterAccess = new Date();
        }
        return cachedChapters;
    }

    public List<Category> loadCategoryStructure(){
        if (lastCategoryAccess==null || new Date().getTime() 
            - lastCategoryAccess.getTime() > 3600000){
            cachedCategories = dao.loadCategoryStructure();
            lastCategoryAccess = new Date();
        }
        return cachedCategories;
    }


}

@ManagedProperty然后使用注释在任何你想要的地方注入 bean :

@ManagedBean
@ViewScoped
public class ViewBean{

    @ManagedProperty(value="#{cacheManager}")
    private CacheManager cacheManager;

    //preRenderView Method
    public void init(){
        chapters = cacheManager.loadChapterStructure();
        categories = cacheManager.loadCategoryStructure();
    }    

}
于 2014-06-30T16:02:04.897 回答