java缓存缓存进行曲之本地缓存框架

本地缓存

  数据类型:业务无关的小数据缓存。

  常见框架:EhCache  纯Java开源缓存框架

    优点:功能强大,有失效策略、最大数量设置等,缓存的持久化只有企业版才有,组件的缓存同步,可以通过jgroup来实现。
    缺点:功能强大的同时,也使其更加复杂。
    EhCahce的核心类:
      A、CacheManager:Cache的管理类;
      B、Cache:具体的cache类信息,负责缓存的get和put等操作
      C、CacheConfiguration :cache的配置信息,包含策略、最大值等信息
      D、Element:cache中单条缓存数据的单位
  
CacheManager manager = CacheManager.newInstance("src/config/ehcache.xml");
manager.addCache("testCache");
Cache test = singletonManager.getCache("testCache");
test.put(new Element("key1", "value1"));
manager.shutdown();
Cache testCache = new Cache(
  new CacheConfiguration("testCache", maxElements)
    .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
    .overflowToDisk(true)
    .eternal(false)
    .timeToLiveSeconds(60)
    .timeToIdleSeconds(30)
    .diskPersistent(false)
    .diskExpiryThreadIntervalSeconds(0));
Ehcache cache = cacheManager.getEhcache("xaCache");
transactionManager.begin();//开启事务
try {
    Element e = cache.get(key);
    Object result = complexService.doStuff(element.getValue());
    cache.put(new Element(key, result));
    complexService.doMoreStuff(result);
    transactionManager.commit();
} catch (Exception e) {
    transactionManager.rollback();
}

  常见框架:guava Google提供的java工具类 很猛

    Guava Cache是一个全内存的本地缓存实现,而且提供了线程安全机制,所以特别适合于代码中已经预料到某些值会被多次调用的场景。

    <dependencies>
      
        <!-- Spring boot Cache-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

        <!--for guava cache-->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0.1-jre</version>
        </dependency>

    </dependencies>

  引入 Guava Cache的配置文件 GuavaCacheConfig

@Configuration
@EnableCaching
public class GuavaCacheConfig {

    @Bean
    public CacheManager cacheManager() {
        GuavaCacheManager cacheManager = new GuavaCacheManager();
        cacheManager.setCacheBuilder(
                CacheBuilder.newBuilder().
                        expireAfterWrite(10, TimeUnit.SECONDS).//缓存存活时间为 10 秒,缓存最大数目为 1000 个
                        maximumSize(1000));
        return cacheManager;
    }
}

  常用注解:

  1. @Cacheable:配置在 getUsersByName方法上表示其返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
  2. @CachePut:配置于方法上时,能够根据参数定义条件来进行缓存,其与 @Cacheable不同的是使用 @CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中,所以主要用于数据新增和修改操作上
  3. @CacheEvict:配置于方法上时,表示从缓存中移除相应数据。

  测试日志:

猜你喜欢

转载自www.cnblogs.com/watchdogzhb/p/10601540.html