ehcache3.8 获取持久化的数据为null

新手上路,请多包涵

static CacheManager cacheManager = null;

static {
    //1、获取到XML文件位置的URL
    URL myUrl = KafkaStreamn.class.getResource("/ehcache.xml");
    //2、实例化一个XmlConfiguration,将XML文件URL传递给它
    Configuration xmlConfig = new XmlConfiguration(myUrl);
    //3、使用静态的org.ehcache.config.builders.CacheManagerBuilder.newCacheManager(org.ehcache.config.Configuration)
    //使用XmlConfiguration的Configuration创建你的CacheManager实例。
    cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
    try {
        cacheManager.init();
//            cacheManager.close();
    } catch (StateTransitionException se) {
        //异常之后就打印堆栈信息
        se.printStackTrace();
        log.info("很抱歉,运行失败!");
        cacheManager.close();
        log.info("关闭cacheManager,否则下次启用的时候会报jvm端口号被占用的异常。");
    }
}

  /**
 * 将Ehcache中的数据持久化
 */
@Test
public void test() {
    Cache<String, String> threeTieredCache = cacheManager.getCache("threeTieredCache4", String.class, String.class);
    threeTieredCache.put("3L", "这是第:3条信息");
    log.info("存储成功:{}", threeTieredCache.get("3L"));
//        cacheManager.close();
    Cache<String, String> threeTieredCache2 = cacheManager.getCache("threeTieredCache4", String.class, String.class);
    log.info("获取成功:{}", threeTieredCache2.get("3L"));
}

2022-03-01 13:49:44 INFO  [main] org.example.KafkaStreamn 存储成功:这是第:3条信息
2022-03-01 13:49:44 INFO  [main] org.example.KafkaStreamn 获取成功:这是第:3条信息

存入可以,


/**
 * 从硬盘读取数据
 */
@Test
public void testCount() {
    Cache<String, String> threeTieredCache3 = cacheManager.getCache("threeTieredCache4", String.class, String.class);
    log.info("获取成功:{}", threeTieredCache3.get("3L"));
}

2022-03-01 13:50:31 INFO  [main] org.example.KafkaStreamn 获取成功:null    

为什么单独写一个方法,在获取就不行,通过get(key)获取的就是null?

阅读 1.3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进