JetCahce

2018-11-06  本文已影响68人  jiangmo

简介

核心功能

使用示例

// 类
public static class Foo extends AbstractCacheTest {
           // 默认缓存 所有配置都默认 
            @CreateCache
            private Cache<Long, User> cacheDefault;  

            // 自定义缓存 不配置则使用默认值
            @CreateCache(
              area = "A1",  // 缓存容器命名空间,区分不同的缓存实例
              name = "name1",  // 缓存容器实例名称,相当于一个Map实例名称
              expire = 50, localExpire = 100, timeUnit = TimeUnit.MILLISECONDS, // 过期时间,远程、本地
              cacheType = CacheType.BOTH, // 多级缓存:本地/远程/二级
              localLimit = 1000, // 本地缓存最大容量
              serialPolicy = SerialPolicy.JAVA, // 远程缓存,Object传输序列化方式
              keyConvertor = KeyConvertor.FASTJSON // Object转为字符串 
              )
            private Cache cacheCustom;
}

// 接口
public interface UserService {
      // 查询注解
    @Cached(
              area = "user-cache",  
              name = "userCache-", 
              expire = 50, localExpire = 100, timeUnit = TimeUnit.MILLISECONDS,
              cacheType = CacheType.BOTH, 
              localLimit = 1000,
              serialPolicy = SerialPolicy.JAVA,
              keyConvertor = KeyConvertor.FASTJSON,
              key = "#user.userId", // key 表达式
              cacheNullValue = true, // 是否缓存null
              condition = "#user.userId < 100000", // 缓存过滤前置条件
    )
    User getUserById(long userId);

     // 更新注解
    @CacheUpdate(name="userCache-", key="#user.userId", value="#user")
    void updateUser(User user);

    // 失效注解
    @CacheInvalidate(name="userCache-", key="#userId")
    void deleteUser(long userId);

    // 定时刷新
    @Cached(expire = 3600, cacheType = CacheType.REMOTE)
    @CacheRefresh(
        refresh = 1800, // 刷新间隔
        stopRefreshAfterLastAccess = 3600,  // 刷新任务失效移除时间
        timeUnit = TimeUnit.SECONDS    // 时间单位
    )
    BigDecimal salesVolumeSummary(int timeId, long catagoryId);
}

// 手动声明
Cache<Long, UserDO> userCache = CellarCacheBuilder.createCellarCacheBuilder()
                .keyConvertor(FastjsonKeyConvertor.INSTANCE) // 选配
                .valueEncoder(JavaValueEncoder.INSTANCE) // 选配
                .valueDecoder(JavaValueDecoder.INSTANCE) // 选配
                .tairClient(tairClient)  // 必填
                ..nameSpace((short) 123) // 必填
                .keyPrefix("userCache-") // 选填
                .expireAfterWrite(200, TimeUnit.SECONDS) // 选填
                .refreshPolicy(RefreshPolicy.newPolicy(60, TimeUnit.SECONDS)) // 选填
                .loader(this::loadOrderSumFromDatabase) // 选填
                .buildCache();
// 当做Map使用
User user = userCache.get(12345L);
userCache.put(12345L, loadUserFromDataBase(12345L));
userCache.remove(12345L);

userCache.computeIfAbsent(1234567L, (key) -> loadUserFromDataBase(1234567L));

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

// 不严格的分布式锁
cache.tryLockAndRun("lock-key", 60, TimeUnit.SECONDS, () -> heavyDatabaseOperation());

引入方式

maven

    <dependency>
        <groupId>com.sankuai.hotel</groupId>
        <artifactId>cache-keeper-ext-cellar</artifactId>
        <version>${cache-keeper-ext-cellar.version}</version>
    </dependency>

App class

@SpringBootApplication
@EnableMethodCache(basePackages = "com.company.mypackage")
@EnableCreateCacheAnnotation
public class MySpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApp.class);
    }
}

spring boot

jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: linkedhashmap
      ...
  remote:
    default:
      type: redis
      ...

关键代码

CacheHandler: 用InvocationHandler自己实现了一套切面逻辑

函数入口:

读缓存:

这里LoaderLock为什么放在一个ConcurrentHashMap中?

可能出现死锁:如果newLoader.apply(key) 一直抛异常

优点

缺点

Ref:
github官网地址:https://github.com/alibaba/jetcache
集成cellar Squirrel git:http://git.sankuai.com/users/haozhongweng/repos/mintcachekeeper/browse

上一篇下一篇

猜你喜欢

热点阅读