14.4. Java缓存标准规范JCache API (JSR-107)

Redisson在Redis的基础上实现了Java缓存标准规范(JCache API JSR-107

以下范例展示了使用Java缓存标准的用法。范例采用了保存在默认路径/redisson-jcache.json/redisson-jcache.yaml下的配置文件构造实例。

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  3. Cache<String, String> cache = manager.createCache("namedCache", config);

也可以采用指定配置文件路径的方式构造实例:

  1. MutableConfiguration<String, String> config = new MutableConfiguration<>();
  2. // JSON格式的配置文件
  3. URI redissonConfigUri = getClass().getResource("redisson-jcache.json").toURI();
  4. // YAML格式的配置文件
  5. URI redissonConfigUri = getClass().getResource("redisson-jcache.yaml").toURI();
  6. CacheManager manager = Caching.getCachingProvider().getCacheManager(redissonConfigUri, null);
  7. Cache<String, String> cache = manager.createCache("namedCache", config);

还可以通过程序化的方式来构造:

  1. MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
  2. Config redissonCfg = ...
  3. Configuration<String, String> config = RedissonConfiguration.fromConfig(redissonCfg, jcacheConfig);
  4. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  5. Cache<String, String> cache = manager.createCache("namedCache", config);

甚至可以用Redisson实例来构造:

  1. MutableConfiguration<String, String> jcacheConfig = new MutableConfiguration<>();
  2. RedissonClient redisson = ...
  3. Configuration<String, String> config = RedissonConfiguration.fromInstance(redisson, jcacheConfig);
  4. CacheManager manager = Caching.getCachingProvider().getCacheManager();
  5. Cache<String, String> cache = manager.createCache("namedCache", config);

关于配置Redisson的方式详见这里

由Redisson提供的JCache(JSR-107)完全符合标准要求并全部通过TCK标准检测。标准检验代码在这里