天天看點

Ehcache在java中的應用

spring 的注解@Cacheable等,并不可以設定失效時間,沿着這個思路,開始實驗怎麼樣設定失效時間才可以生效。

試驗一:springboot啟動類加注解@EnableCaching開啟緩存,需要加入緩存的方法上加@Cacheable注解。

試驗一結果:緩存生效,重新開機服務後,緩存失效。

試驗二:使用@Cacheable注解,建立ehcache.xml,看ehcache.xml上面配置的緩存失效時間是否生效

試驗二結果:ehcache.xml中配置的緩存失效時間并沒有生效。

試驗三:ehcache.xml 配合CacheManager 看緩存失效時間是否生效

試驗三結果: 緩存生效。

代碼說明

一 pom.xml檔案

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.6</version>
</dependency>
           

二 import

import com.example.demo.po.User;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
           

三 代碼部分

@RequestMapping("/testPut")
public String testPut() {
    // 從資料庫取值
    List<User> user = cacheService.getUser();
    // 建立緩存,預設ehcache-failsafe.xml的配置
    // todo 本地建立ehcache.xml 怎樣才能生效
    CacheManager cacheManager = CacheManager.create();
    Cache cache = cacheManager.getCache("user");
    Element element = new Element("key", user);
    cache.put(element);
    return "main";
}
@RequestMapping("/testGet")
public String testGet() {
    CacheManager cacheManager = CacheManager.create();
    // 從緩存中取值,預設的xml檔案中配置失效時間是2min,2min後再調接口,空指針異常。
    // 如果使用cachename是緩存中沒有的,cache對象為null。已驗證
    // 如果key值是cachename中沒有的,element對象為null。已驗證
    Cache cache = cacheManager.getCache("user");
    Element element = cache.get("key1");
    int a = ((List)element.getObjectValue()).size();
    return "main";
}