ehcache映射<String,Entry>在springboot中无法工作

huangapple go评论65阅读模式
英文:

ehcache Map<String,Entry> not work springboot

问题

我尝试过缓存Map<String, Entry>但每次调用getEntries()都会在没有缓存的情况下命中数据库
同时我还对Entry对象进行了序列化请提供支持

@Cachable("stocks")
public Map<String, Entry> getEntries() {
    // 从数据库获取entry,然后转换为map
    return map;
}
英文:

i tried to cache Map<String,Entry> , but every time i found getEntries() hit database without caching ,
also i serialize Entry object , please yours support

@Cachable(&quot;stocks&quot;)
 public Map&lt;String,Entry&gt; getEntries(){
    //getting entry from database then convert to map
  return map;
 }

答案1

得分: 1

这对我有效

@Service
public class OrderService {

    public static int counter = 0;

    @Cacheable("stocks")
    public Map<String, Entry> getEntries() {
        counter++;
        final Map<String, Entry> map = new HashMap<>();
        map.put("key", new Entry(123l, "有趣的条目"));
        return map;
    }
}

这是一个用来证明计数器未被调用的测试

@Test
public void entry() throws Exception {
    OrderService.counter = 0;
    orderService.getEntries();
    assertEquals(1, OrderService.counter);
    orderService.getEntries();
    assertEquals(1, OrderService.counter);
}

我已将所有内容添加到我的github示例中。

英文:

This works for me

@Service
public class OrderService {

    public static int counter = 0;

    @Cacheable(&quot;stocks&quot;)
    public Map&lt;String, Entry&gt; getEntries() {
        counter++;
        final Map&lt;String, Entry&gt; map = new HashMap&lt;&gt;();
        map.put(&quot;key&quot;, new Entry(123l, &quot;interesting entry&quot;));
        return map;
    }
}

Here's a test to prove the counter is not called.

   @Test
    public void entry() throws Exception {
        OrderService.counter = 0;
        orderService.getEntries();
        assertEquals(1, OrderService.counter);
		orderService.getEntries();
        assertEquals(1, OrderService.counter);
    }

I've added it all to my github example

huangapple
  • 本文由 发表于 2020年10月4日 16:48:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64192709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定