【问题标题】:Spring MVC - Loading reference data from second level cacheSpring MVC - 从二级缓存加载参考数据
【发布时间】:2012-12-02 12:59:37
【问题描述】:

我正在继续我之前提出的问题(下面的链接)

Spring MVC - Get reference data from database on server startup

在得到一些关于之前帖子的建议后,我认为我可以用来加载参考数据的方法是,在 ArticleController(我的控制器类)中添加以下方法

    @ModelAttribute
    public void populateModel(@RequestParam String number, Model model) {
        model.addAttribute("countryList", articleService.getCountryList());
        model.addAttribute("skillsList", articleService.getSkillsList());
    }

然后像下面这样使用休眠二级缓存,

    @Entity
    @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
    public class Country {
        ...
    }

技能类也是如此

我有三个问题

  1. populateModel 方法(@ModelAttribute)是否只执行一次?即在 ArticleController 类上执行第一个 @RequestMapping 方法之前(对于多个会话中的所有请求 - 我在日志跟踪中看到 ArticleController 在我启动服务器时被初始化)?
  2. 除了我提到的实现二级缓存之外,我还需要做更多的事情吗? (contry 列表和技能列表是两个单独表格中的纯只读数据)
  3. 任何我遗漏的点,您都可以提出建议。

【问题讨论】:

  • 你看过code.google.com/p/ehcache-spring-annotations的Spring EhCache项目吗?我用它来做你所描述的事情——它基本上缓存了一个方法的响应,并让你能够设置刷新之前的时间段等。使用(注释)和设置非常简单。

标签: mysql hibernate spring-mvc drop-down-menu


【解决方案1】:
  1. 没有。如the documentation 中所述,将为每个请求调用该方法。顺便说一句,如果它只被调用一次,它会在哪里找到请求参数(你不使用,顺便说一句)?

  2. 如果除了二级缓存之外没有开启查询缓存,并且使查询可缓存,那么Hibernate每次都会执行一个SQL查询从数据库中加载国家ID,然后从二级缓存加载实体本身。如果启用了查询缓存并且查询是可缓存的,那么 Hibernate 将执行单个查询以加载缓存中的所有国家/地区,之后不再执行任何查询(至少对于缓存区域的 TTL)

  3. 我想我已经做了我能做的:-)。您可以阅读the following article 以获得更好的理解。

【讨论】:

【解决方案2】:

针对问题1,这个方法:

@ModelAttribute
    public void populateModel(@RequestParam String number, Model model) {
        model.addAttribute("countryList", articleService.getCountryList());
        model.addAttribute("skillsList", articleService.getSkillsList());
    }

标有@ModelAttribute 注释。这意味着每次调用此控制器中的任何 @RequestMapping 注释方法时(之前)都会执行该方法。

如果您要缓存一些模型属性,最好将它们公开为@RequestMapping 方法。

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 2016-07-17
    • 2012-12-12
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 2013-09-05
    • 2017-03-31
    • 1970-01-01
    相关资源
    最近更新 更多