JetCache总结

特性

全部特性:

  • 通过统一的API访问Cache系统
  • 通过注解实现声明式的方法缓存,支持TTL和两级缓存
  • 通过注解创建并配置Cache实例
  • 针对所有Cache实例和方法缓存的自动统计
  • Key的生成策略和Value的序列化策略是可以配置的
  • 分布式缓存自动刷新,分布式锁 (2.2+)
  • 异步Cache API (2.2+,使用Redis的lettuce客户端时)
  • Spring Boot支持

JetCache整合srpingboot配置

maven配置

   
   
        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
         
    
      
      
            com.alicp.jetcache
            jetcache-starter-redis
            2.6.0
        
        
        
     
       org.apache.maven.plugins
       maven-compiler-plugin
       3.8.0
       
       1.8
       1.8
       -parameters
       
      

application.yml配置

jetcache:
  statIntervalMinutes: 1
  areaInCacheName: false
  local:
    default:
      type: caffeine
      limit: 100
      keyConvertor: fastjson
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 5
        maxIdle: 20
        maxTotal: 50
      host: 47.98.129.125
      port: 6379
      #password:***
      #sentinels: 127.0.0.1:26379 , 127.0.0.1:26380, 127.0.0.1:26381
      #masterName: mymaster

使用JavaConfig配置(与application.yml配置二选一)

@Configuration
@EnableMethodCache(basePackages = "com.example.demo.cache")
@EnableCreateCacheAnnotation
public class JetCacheConfig {

    @Bean
    public Pool<Jedis> pool() {
        GenericObjectPoolConfig pc = new GenericObjectPoolConfig();
        pc.setMinIdle(2);
        pc.setMaxIdle(10);
        pc.setMaxTotal(10);
        return new JedisPool(pc, "47.98.129.125", 6379);
    }

    @Bean
    public ConfigProvider configProvider() {
        return new ConfigProvider();
    }

    @Bean
    public GlobalCacheConfig config( Pool<Jedis> pool) {
        Map localBuilders = new HashMap();
        EmbeddedCacheBuilder localBuilder = CaffeineCacheBuilder
                .createCaffeineCacheBuilder()
                .limit(100)
                .keyConvertor(FastjsonKeyConvertor.INSTANCE);

        localBuilders.put(CacheConsts.DEFAULT_AREA, localBuilder);

        Map remoteBuilders = new HashMap();
        RedisCacheBuilder remoteCacheBuilder = RedisCacheBuilder.createRedisCacheBuilder()
                .keyConvertor(FastjsonKeyConvertor.INSTANCE)
                .valueEncoder(JavaValueEncoder.INSTANCE)
                .valueDecoder(JavaValueDecoder.INSTANCE)
                .jedisPool(pool);
        remoteBuilders.put(CacheConsts.DEFAULT_AREA, remoteCacheBuilder);

        GlobalCacheConfig globalCacheConfig = new GlobalCacheConfig();
        globalCacheConfig.setLocalCacheBuilders(localBuilders);
        globalCacheConfig.setRemoteCacheBuilders(remoteBuilders);
        globalCacheConfig.setStatIntervalMinutes(15);
        globalCacheConfig.setAreaInCacheName(false);
        return globalCacheConfig;
    }
}

常用注解

启动类上加注解,开启缓存:

@EnableMethodCache(proxyTargetClass = true,basePackages = "com.shinemo.migu.activity.thirdapi.core")
@EnableCreateCacheAnnotation

方法上的注解

获取时:

@Cached(name = "award.getById", key = "#id", cacheType = CacheType.LOCAL, expire = 300)

修改时:

 @CacheUpdate(name="userCache-", key="#user.userId", value="#user")
 void updateUser(UserDO user);

删除时:

@CacheInvalidate(name = "userService2.getUserById", key = "#id")

代码示例:

@Service
public class UserService2 {

    @Autowired
    private UserDao userDao;

    @Cached(name = "userService2.getUserById", key = "#id", cacheType = CacheType.BOTH, expire = 60*5)
    @CacheRefresh(refresh = 10, stopRefreshAfterLastAccess = 60)
    public UserDO getUserById(Integer id) {
        UserDO userDO = userDao.selectById(id);
        return userDO;
    }

    public void addUser(UserDO user) {
        userDao.insert(user);
    }

    @CacheUpdate(name = "userService2.getUserById", key = "#user.id",value = "#user" )
    public void updateUser(UserDO user) {
        userDao.updateById(user);
    }

    @CacheInvalidate(name = "userService2.getUserById", key = "#id")
    public void deleteUser(Integer id) {
        //userDao.deleteById(id);
    }
}

实例变量上的注解

创建缓存实例:

@CreateCache(cacheType = CacheType.LOCAL, name = "jobActivityCache", timeUnit = TimeUnit.MINUTES, expire = 5)
private Cache userCache;

@CreateCache(name = "UserService.userCache", expire = 100, cacheType = CacheType.BOTH, localLimit = 50)
private Cache userCache;

代码示例:

@Service
public class UserService {

    @CreateCache(name = "UserService.userCache", cacheType = CacheType.REMOTE, localLimit = 50,expire = 60*5)
    private Cache<Integer, UserDO> userCache;

    @Autowired
    private UserDao userDao;

    public UserDO getUserById(Integer id) {
        UserDO userDO = userCache.get(id);
        if (userDO == null) {
            UserDO userDB = userDao.selectById(id);
            if (userDB == null) {
                throw new RuntimeException("数据不存在");
            }
            userCache.put(id, userDB);
            return userDB;
        }
        return userDO;
    }

    public void addUser(UserDO user) {
        userDao.insert(user);
    }

    public void updateUser(UserDO user) {
        userDao.updateById(user);
        userCache.put(user.getId(), user);
    }

    public void deleteUser(Integer id) {
        //userDao.deleteById(id);
        userCache.remove(id);
    }
}

刷新缓存

@CacheRefresh

刷新缓存,可以加在方法上,也可以加在实例上:

@CacheRefresh(refresh = 60, stopRefreshAfterLastAccess = 300) //60秒刷新一次,如果300秒内没有访问,则停止刷新

cacheType为REMOTE或者BOTH的时候,刷新行为是全局唯一的,也就是说,即使应用服务器是一个集群,也不会出现多个服务器同时去刷新一个key的情况。
一个key的刷新任务,自该key首次被访问后初始化,如果该key长时间不被访问,在stopRefreshAfterLastAccess指定的时间后,相关的刷新任务就会被自动移除,这样就避免了浪费资源去进行没有意义的刷新。

@CachePenetrationProtect

@CachePenetrationProtect表示在多线程环境中同步加载数据。

高级API

异步API

CacheGetResult r = cache.GET(userId);
CompletionStage<ResultData> future = r.future();
future.thenRun(() -> {
    if(r.isSuccess()){
        System.out.println(r.getValue());
    }
});

分布式锁

cache.tryLockAndRun("key", 60, TimeUnit.SECONDS, () -> heavyDatabaseOperation());

设置读取器并自动刷新

    @CreateCache(name = "UserService3.userCache",timeUnit = TimeUnit.SECONDS,expire = 1000,cacheType = CacheType.BOTH)
    @CacheRefresh(timeUnit = TimeUnit.SECONDS, refresh = 30, stopRefreshAfterLastAccess = 600)
    @CachePenetrationProtect
    private Cache> userCache;

    @PostConstruct
    public void init(){
        userCache.config().setLoader(this::loadUser);
    }
    public List loadUser(String key) {
        List userDOS = userDao.selectList(null);
        return userDOS;
    }

你可能感兴趣的:(缓存)