Ehcache缓存框架入门级使用

前言

JAVA缓存实现方案有很多,最基本的自己使用Map去构建缓存,或者使用memcached或Redis,但是上述两种缓存框架都要搭建服务器,而Map自行构建的缓存可能没有很高的使用效率,那么我们可以尝试一下使用Ehcache缓存框架。

Ehcache主要基于内存缓存,磁盘缓存为辅的,使用起来方便。下面介绍如何在项目中使用Ehcache

入门使用教程

1.maven引用


  net.sf.ehcache
  ehcache
  2.10.4

2.在classpath下建立一个ehcache.xml



 
 

    
    
    
    
        
    
    
    
    

3.与spring的cacheManager结合使用




    
    

    
    
        
    

    
    
        
        
    


4.代码使用


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.easylink.mall.entity.Merchant;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class EhcacheTest {

    @Autowired
    private CacheManager cacheManager;

    @Test
    public void execute() {
        // 获取商户申请缓存容器
        Cache cache = cacheManager.getCache("merchant-apply-cache");
        Merchant merchant = new Merchant();
        Long id = IdWorker.getId();
        merchant.setId(id);
        merchant.setName("缓存测试");
        // 将商户申请数据添加至缓存中 // key : id value : object
        cache.put(id, merchant);
        // 获取商户申请数据
        // 方法1
        Merchant cacheMerchant1 = (Merchant) cache.get(id).get();
        System.out.println(cacheMerchant1.getName());
        // 方法2
        Merchant cacheMerchant2 = cache.get(id, Merchant.class);
        System.out.println(cacheMerchant2.getName());
        // 将商户申请数据从缓存中移除
        cache.evict(id);
    }

}

5.注意事项

cache.get(key) 和cache.get(key, class);方法,由于不知道你存入的key是什么类型,所以get的时候不会做key的类型检查,如上述例子中

Long id = IdWorker.getId();
cache.put(id, merchant);
Merchant cacheMerchant2 = cache.get(id, Merchant.class);

put进去时的key是Long类型的,get的时候也只能传入对应Long类型的key才能获取到对应的value,如果传入的是String类型的key,即使两个key的值是一致的,也会导致无法获取到对应的value。这个情况很容易发生在对request请求的参数,由于是String字符串类型,但是忘了做类型转换就直接把这个String当做key去获取对应的value。导致获取不到,请同学们要注意,亲身经历,血与泪的教训。

总结

以上就是我自己总结的Ehcache入门级用法,Ehcache是个不错的内存缓存框架,如果没使用过的话,可以尝试使用。

你可能感兴趣的:(Ehcache缓存框架入门级使用)