Caffeine Cache 缓存框架进阶学习

Caffeine Cache 进程缓存之王
https://www.java1000.com/89843.html
https://www.cnblogs.com/rickiyang/p/11074158.html

spring cache
http://www.cppcns.com/ruanjian/java/189741.html

以下为简单的查询,查询缓存,删除缓存

pom:


		
			com.github.ben-manes.caffeine
			caffeine
			2.6.2
		
		
			org.springframework.boot
			spring-boot-starter-cache
		


/**
 * @Classname CacheConfig
 * @Description TODO
 * @Date 2020/7/31 10:13
 * @Created by Administrator
 */
@Configuration
public class CacheConfig {
        /**
     * 相当于在构建LoadingCache对象的时候 build()方法中指定过期之后的加载策略方法
     * 必须要指定这个Bean,refreshAfterWrite=60s属性才生效
     * @return
     */
    @Bean
    public CacheLoader cacheLoader() {
        CacheLoader cacheLoader = new CacheLoader() {
            @Override
            public Object load(String key) throws Exception {
                return null;
            }
            // 重写这个方法将oldValue值返回回去,进而刷新缓存
            @Override
            public Object reload(String key, Object oldValue) throws Exception {
                return oldValue;
            }
        };
        return cacheLoader;
    }

    /**
     * 创建基于Caffeine的Cache Manager
     * 初始化一些key存入
     * @return
     */
    @Bean
    @Primary
    public CacheManager caffeineCacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        ArrayList caches = Lists.newArrayList();
        List list = setCacheBean();
        for(CacheBean cacheBean : list){
            //
            caches.add(new CaffeineCache(cacheBean.getKey(),
                    Caffeine.newBuilder().recordStats()
                            .expireAfterWrite(cacheBean.getTtl(), TimeUnit.SECONDS)
                            .maximumSize(cacheBean.getMaximumSize())
                            .build()));
            //统计 可以打开统计信息收集。Cache.stats() 方法返回提供统计信息的CacheStats
            caches.add(new CaffeineCache(cacheBean.getKey(),
                    Caffeine.newBuilder().maximumSize(1000).recordStats().build()));
        }
        cacheManager.setCaches(caches);
        return cacheManager;
    }

    /**
     * 初始化一些缓存的 key
     * @return
     */
    private List setCacheBean(){
        List list = Lists.newArrayList();
        CacheBean userCache = new CacheBean();
        userCache.setKey("userCache");
        userCache.setTtl(60);
        userCache.setMaximumSize(10000);

        CacheBean deptCache = new CacheBean();
        deptCache.setKey("deptCache");
        deptCache.setTtl(60);
        deptCache.setMaximumSize(10000);

        list.add(userCache);
        list.add(deptCache);

        return list;
    }
}
package com.netty.lj.model;

import lombok.Data;

import java.io.Serializable;

/**
 * @Classname CacheBean
 * @Description TODO
 * @Date 2020/7/31 10:12
 * @Created by Administrator
 */
@Data
public class CacheBean implements Serializable {
    private String key;
    private long ttl;
    private long maximumSize;
}

  /**
     * 查找
     * 先查缓存,如果查不到,会查数据库并存入缓存  @Cacheable
     * @param id
     */
    @RequestMapping(value="/baseUser",method=RequestMethod.GET)
    @ResponseBody
    @Cacheable(value = "userCache", key = "#id", sync = true)
    public UserDO testCache(@RequestParam(value = "id",required = false)String id) {
        long date1 = System.currentTimeMillis();
        logger.info(date1);
        UserDO userDO = nettyService.testCache(id);
        logger.info(System.currentTimeMillis()-date1);
        return userDO;
    }

    /**
     * @Author LJ
     * @Description 获取缓存
     * @Date 15:13 2020/7/31
     * @Param [id]
     * @return com.netty.lj.model.UserDO
     **/
    @RequestMapping(value="/getUserCache",method=RequestMethod.GET)
    @ResponseBody
    @Cacheable(value = "userCache", key = "#id", sync = true)
    public UserDO getUserCache(@RequestParam(value = "id",required = false)String id) {
        UserDO nativeCache = null;
        Cache cache = cacheManager.getCache(id);
        //防止空指针
        if (cache !=null){
            nativeCache = (UserDO) cache.getNativeCache();
        }
        return nativeCache;
    }


    /**
     * 删除缓存 @CacheEvict
     * @param id
     */
    @RequestMapping(value="/deleteUserCacheById",method=RequestMethod.GET)
    @ResponseBody
    @CacheEvict(value = "userCache",key = "#id")
    public void deleteUserCacheById(@RequestParam(value = "id",required = false)String id) {
    }

你可能感兴趣的:(SpringBoot)