JetCache Documentation

repository·master·Indexed 26 days ago

https://github.com/alibaba/jetcache

JetCache is a high-performance Java cache abstraction library providing a unified API for backends such as Redis, Caffeine, and Tair. It features declarative method caching via annotations with native support for TTL, two-level caching, distributed automatic refresh, and distributed locks. It offers full Spring Boot integration and supports asynchronous cache access when using the Lettuce Redis client. Version 2.8+ requires JDK 17+, Spring Framework 6.x+, and Spring Boot 3.x+, while version 2.7 and below support JDK 8+.

Tokens
34.7K
Snippets
83
Records
130
Agent score
84%

What's inside JetCache

  1. Introduction to JetCache

    master

    JetCache is a Java cache abstraction that provides a uniform API for various caching solutions, including RedisCache, TairCache, CaffeineCache (in-memory), and LinkedHashMapCache (in-memory).

    Key features include:

    • Declarative method caching via annotations with TTL and two-level caching support.
    • Manual cache manipulation using the Cache API.
    • Support for distributed cache auto-refresh and distributed locks.
    • Customization of key generation and value serialization (supports fastjson2, jackson, jackson3 for keys; java, kryo, kryo5 for values).
    • Asynchronous access and local cache invalidation across JVM processes.
  2. Overview of JetCache features

    master

    JetCache is a Java cache abstraction layer that provides a consistent API for various caching solutions. Key features include:

    • Consistent Cache API: Operate different cache implementations using the same interface.
    • Declarative Method Caching: Use annotations to implement caching with native TTL (Time To Live) and two-level caching support.
    • Customizable Policies: Customize key generation and value serialization.
    • Advanced Capabilities: Distributed cache automatic refreshment, distributed locks, and asynchronous access (using Redis Lettuce client).
    • Statistics: Automatic collection of access statistics for both Cache instances and method caches.
    • Spring Support: Full support for Spring Boot and Spring Framework.
  3. Overview of JetCache

    master

    JetCache is a Java-based cache system wrapper that provides a unified API and annotations to simplify cache usage. It offers more powerful annotations than SpringCache, including native support for TTL (Time-To-Live), two-level caching, and distributed automatic refresh. It also provides a Cache interface for manual cache operations.

    Key features include:

    • Unified API for accessing cache systems.
    • Declarative method caching via annotations (supports TTL and two-level caching).
    • Annotation-based creation and configuration of Cache instances.
    • Automatic statistics for all Cache instances and method caches.
    • Configurable Key generation and Value serialization strategies.
    • Distributed cache automatic refresh and distributed locks (2.2+).
    • Asynchronous Cache API (2.2+, when using the Lettuce Redis client).
    • Spring Boot support.
  4. Understand JetCache core components and implementations

    master

    JetCache is divided into the Cache API (and its implementations) and Annotation support.

    Core Cache Implementations

    The Cache interface is the central API. Key implementations include:

    • RedisCache: Redis implementation using the Jedis client.
    • RedisLettuceCache: Redis implementation using the Lettuce client.
    • CaffeineCache: In-memory cache based on Caffeine.
    • LinkedHashMapCache: A simple, zero-dependency in-memory cache.
    • LoadingCache: Uses the Decorator pattern to provide automatic loading functionality.
    • RefreshCache: Uses the Decorator pattern to provide automatic refresh functionality.
    • MultiLevelCache: Supports N-level caching (though annotation-based configuration currently supports two levels).

    Annotation Support

    jetcache-anno provides annotation support. The primary entry points are:

    • EnableCreateCacheAnnotation
    • EnableMethodCache

    Spring Boot Integration

    Spring Boot configuration support is located in the jetcache-starter module.

  5. Expose JedisSentinelPool as a Spring Bean

    master

    Use JedisPoolFactory with JedisSentinelPool.class to create a Sentinel pool bean.

    @Bean(name = "defaultSentinelPool")
    @DependsOn(RedisAutoConfiguration.AUTO_INIT_BEAN_NAME)//jetcache2.2+
    public JedisSentinelPool defaultSentinelPool() {
        return new JedisPoolFactory("remote.default", JedisSentinelPool.class);
    }
    
    @Autowired
    private JedisSentinelPool defaultSentinelPool;
  6. Create a Cache instance using CacheManager

    master

    In JetCache 2.7 and later, the @CreateCache annotation is deprecated. Instead, use CacheManager.getOrCreateCache(QuickConfig) to programmatically create or retrieve a Cache instance. This method returns the same Cache instance if the area and name match an existing one.

    To use this, build a QuickConfig object using the QuickConfig.newBuilder(name) method and configure your desired settings such as expiration, cache type, and synchronization.

    @Autowired
    private CacheManager cacheManager;
    private Cache<String, UserDO> userCache;
    
    @PostConstruct
    public void init() {
        QuickConfig qc = QuickConfig.newBuilder("userCache")
            .expire(Duration.ofSeconds(100))
            .cacheType(CacheType.BOTH) // two level cache
            .syncLocal(true) // invalidate local cache in all jvm process after update
            .build();
        userCache = cacheManager.getOrCreateCache(qc);
    }
  7. Configure JetCache with Lettuce without Spring Boot

    master

    In non-Spring Boot environments, you must manually define a RedisClient bean and a GlobalCacheConfig bean. Use RedisLettuceCacheBuilder to construct the remote cache configuration. Note that for JetCache 2.7+, you should @Import(JetCacheBaseBeans.class) in your configuration class.

    @Configuration
    @EnableMethodCache(basePackages = "com.company.mypackage")
    @EnableCreateCacheAnnotation
    @Import(JetCacheBaseBeans.class)
    public class JetCacheConfig {
    
        @Bean
        public RedisClient redisClient(){
            RedisClient client = RedisClient.create("redis://127.0.0.1");
            client.setOptions(ClientOptions.builder().
                   disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS)
                   .build());
            return client;
        }
    
        @Bean
        public GlobalCacheConfig config(RedisClient redisClient){
            Map localBuilders = new HashMap();
            EmbeddedCacheBuilder localBuilder = LinkedHashMapCacheBuilder
                    .createLinkedHashMapCacheBuilder()
                    .keyConvertor(Fastjson2KeyConvertor.INSTANCE);
            localBuilders.put(CacheConsts.DEFAULT_AREA, localBuilder);
    
            Map remoteBuilders = new HashMap();
            RedisLettuceCacheBuilder remoteCacheBuilder = RedisLettuceCacheBuilder.createRedisLettuceCacheBuilder()
                    .keyConvertor(Fastjson2KeyConvertor.INSTANCE)
                    .valueEncoder(JavaValueEncoder.INSTANCE)
                    .valueDecoder(JavaValueDecoder.INSTANCE)
                    .broadcastChannel("projectA")
                    .redisClient(redisClient);
            remoteBuilders.put(CacheConsts.DEFAULT_AREA, remoteCacheBuilder);
    
            GlobalCacheConfig globalCacheConfig = new GlobalCacheConfig();
            globalCacheConfig.setLocalCacheBuilders(localBuilders);
            globalCacheConfig.setRemoteCacheBuilders(remoteBuilders);
            globalCacheConfig.setStatIntervalMinutes(15);
            globalCacheConfig.setAreaInCacheName(false);
    
            return globalCacheConfig;
        }
    }
  8. Use Lettuce as the Redis client in Spring Boot

    master

    To use Lettuce for Redis access in a Spring Boot environment, include the jetcache-starter-redis-lettuce Maven artifact. Lettuce uses Netty to establish and reuse a single connection, so connection pool configuration is not required.

    Configure the jetcache.remote.default.type to redis.lettuce in your application.yml. You can configure standard Redis, Redis Sentinel, or Redis Cluster modes.

    jetcache: 
      areaInCacheName: false
      remote:
        default:
          type: redis.lettuce
          keyConvertor: fastjson2 # Options: fastjson(same as fastjson2), jackson, jackson3
          broadcastChannel: projectA
          uri: redis://127.0.0.1:6379/
  9. Configure keyConvertor for jetcache-anno annotations

    master
    When using the Cache API in jetcache-core, the keyConvertor is optional because the local cache uses equals to identify keys. However, if you are using annotations from jetcache-anno (such as @Cached and @CreateCache), you must specify a keyConvertor.
  10. Enable Cache Monitoring via Configuration

    master
    To enable automatic monitoring for caches configured via @CreateCache or @Cached, set the jetcache.statIntervalMinutes property in your YAML configuration to a value greater than 0. JetCache will periodically output statistical information to your logs at the specified interval.
  11. Create a manual Cache instance using CacheManager

    master

    You can manually create and manage Cache instances using a CacheManager. This is useful when you need fine-grained control over cache configuration like TTL (Time To Live) or cache types (e.g., BOTH for two-level caching).

    Use QuickConfig.newBuilder(name) to define the cache settings, then retrieve the instance via cacheManager.getOrCreateCache(qc).

    @Autowired
    private CacheManager cacheManager;
    
    private Cache<Long, UserDO> userCache;
    
    @PostConstruct
    public void init() {
        QuickConfig qc = QuickConfig.newBuilder("userCache") // name used in statistical information
            .expire(Duration.ofSeconds(100))
            //.cacheType(CacheType.BOTH) // create two level cache
            //.localLimit(100) // limit for local cache elements, only used for CacheType.LOCAL and CacheType.BOTH
            //.syncLocal(true) // invalidate local cache in other JVM after updates, only used for CacheType.BOTH, need set broadcastChannel in configuration. 
            .build();
        userCache = cacheManager.getOrCreateCache(qc);
    }
    
    // Usage like a map
    UserDO user = userCache.get(123L);
    userCache.put(123L, user);
    userCache.remove(123L);