Detailed explanation of jetcache usage in springboot environment

jetcache

Brief introduction to the
github address ; jetcache has the advantage of providing more powerful annotation operations than spring cache, and provides two-level caching, local caching and remote caching (redis), asynchronous cache API operations, and other TTLs, etc.

Some content comes from the official website, this article is only for communication and learning

use

Used in springboot

pom

  <dependency>
            <groupId>com.alicp.jetcache</groupId>
            <artifactId>jetcache-starter-redis-lettuce</artifactId>
            <version>2.6.0</version>
        </dependency>

Configuration file

jetcache:
  areaInCacheName: false  #是否加入到cachename中作为前缀
  statIntervalMinutes: 15  #统计间隔时间
  remote:
    default:  #区域area 名
      type: redis.lettuce  #缓存类型
      keyPrefix: test # 全局key前缀
      keyConvertor: fastjson # key序列化
#      valueEncoder: bean:jsonEncoder #value序列化,默认java序列化
#      valueDecoder: bean:jsonDecoder
      readFrom: master #从那些节点读数据,master,masterPreferred,slave,slavePreferred,nearest
      expireAfterWriteInMillis: 1000 # 过期时间,单位毫秒
      #mode: MasterSlave(主从模式) #集群模式
      uri:
        - redis://172.0.0.1:6379
  local:
    default:
      type: caffeine  # 本地缓存使用什么方式,其他还有linkedhashmap
      limit: 100  # 默认100

In addition, add annotations to the configuration class

// 开启在方法上使用缓存注解
@EnableMethodCache(basePackages = "com.xiaodu.jetcache")

// 开启使用注解方式创建cache
@EnableCreateCacheAnnotation

Annotation

annotation Attributes Description
@cached cache data name The name of the cache instance, which can be used as a prefix for displaying statistics and as a key
area Cache area, default is default
key Cache key, use spel expression
expire Expire time. If localExpire is not configured, both local cache and remote cache use this
localExpire Local cache expiration time
cacheType Cache type, optional EMOTE (remote), LOCAL (local), BOTH (second level cache)
localLimit Maximum number of local caches
cacheNullValue Whether to cache null
serialPolicy Serialization method, global is used by default
condition Use SpEL to specify conditions, and query in the cache only when the expression returns true
@CacheUpdate Update cache name The name of the cache instance, which can be used as a prefix for displaying statistics and as a key
area Cache area, the default is default, generally do not need to be set
name Same as @cached.name, cache instance name
key Same as @cached.key, specified using spel expression
value Use spel expressions to specify cache data
condition Cache condition, true to update the cache, false to not update the cache, use spel to specify
@CacheInvalidate delete cache Same as @cacheUpdate The cache is invalid, used when deleting the cache
@CachePenetrationProtect Cache penetration protection, the principle is to lock concurrently, only one thread can execute within the timeout period, and other threads wait value Default true, whether to open
timeout Guard time, default integer maximum value, other threads wait for timeout time, execute method after timeout
timeUnit Time unit, default second
@CacheRefresh cache refresh refresh Refresh interval
timeUnit Time unit, default second
stopRefreshAfterLastAccess Specify how long the key has no access to stop refreshing, if not specified, it will keep refreshing
refreshLockTimeout When the cache of type BOTH/REMOTE is refreshed, only one server will be refreshed at the same time. This server will place a distributed lock in the remote cache. This configuration specifies the lock timeout period. The default lock timeout period is 60s
@CreateCache, annotate to create a cache on the attribute and inject it into spring Same as @cached Slightly, the detailed explanation is the same as @cached

@cached
acts on the method, the class must be a springbean, and the key uses the spel expression

    @Cached(area = "default", name = "test.", key = "'str'", expire = 30,
            localExpire =3, cacheType = CacheType.REMOTE, timeUnit = TimeUnit.SECONDS, localLimit = 5,
    /*serialPolicy = ""*/cacheNullValue = true)
    public Object getstr() {
    
    
        System.out.println("str...");
        return "str...";
    }

@CacheUpdate
acts on the method, the class must use spel expressions for a springbean, key and value

   @CacheUpdate(name = "test.", key = "'str'" ,value = "#result")
    public Object getstrupdate() {
    
    
        return "update";
    }

@CacheRefresh

// 每隔10秒钟 就刷新下缓存
    @Cached(area = "default", name = "test.", key = "'str'", expire = 3,
            localExpire =3, cacheType = CacheType.REMOTE, timeUnit = TimeUnit.SECONDS, localLimit = 5,
    /*serialPolicy = ""*/cacheNullValue = true)
    @CacheRefresh(refresh = 10)
    public Object getstr() {
    
    
        System.out.println("str...");
        return "str...";
    }

@CachePenetrationProtect
added cache penetration protection is at the JVM level, the process level is not distributed; it only protects the service, and only one concurrently acquires the lock to execute, and the others wait

     @Cached(area = "default", name = "test.", key = "'str'", expire = 3,
            localExpire =3, cacheType = CacheType.REMOTE, timeUnit = TimeUnit.SECONDS, localLimit = 5)
    @CachePenetrationProtect
    public Object getstr() {
    
    
        System.out.println("str...");
        return "str...";
    }

@CacheInvalidate
delete cache

   @CacheInvalidate(name = "test.", key = "'str'")
    public void delCache() {
    
    
        System.out.println("delCache name = test. , key = str");
    }

@createCache use

添加@EnableCreateCacheAnnotation开启,createCache的属性和cached注解的属性大致一样

Common api operations

// 直接在springbean属性上添加,
 @CreateCache(area = "default", name = "test.createCache.", expire = 3, cacheType = CacheType.BOTH)
    private Cache<String, Object> cache;
	
	// 操作 cahce的所有方法操作, 大写的是异步的,小写的是同步的,不过小写的没返回值的 也是异步的;底层还是调用的异步操作方法,有返回值的也是调用的异步操作方法 不过在获取返回值的时候阻塞了
    public void testCreateCache() {
    
    
    	// 添加缓存
        cache.put("key1", "value2");
        // 添加缓存, 并设置超时时间, 若没设置超时时间则以注解上的设置为准
        cache.put("key2", "value2", 10, TimeUnit.SECONDS);
        // 如果key对应的value不存在,则添加缓存value
        cache.putIfAbsent("key1", "newValue2");
        // 如果key对应的value不存在,则通过function 获取,并关联key,添加到缓存
        cache.computeIfAbsent("key1", e -> "computeValue");
		/*
		以上put 添加缓存的操作都是异步的
		*/	
		
		// 同步获取缓存
        Object key1 = cache.get("key1");
        // 异步获取
        CacheGetResult<Object> key11 = cache.GET("key1");
        // 删除缓存
        boolean key2 = cache.remove("key2");
        // 异步删除缓存, isSuccess()会阻塞获取结果
        boolean key21 = cache.REMOVE("key2").isSuccess();
		
		// CompletableFuture 操作;cache的异步操作可以像CompletableFuture一样,进行异步异步操作
		  cache.GET("key1").future()
                .thenComposeAsync(e -> CompletableFuture.runAsync(() -> {
    
    
                    System.out.println(e.getResultCode());
                }))
                .thenAccept(e -> {
    
    
                    System.out.println("cache thenaccept");
                });
	
		// 分布式锁操作, 这个需要lock.close() 并且需要判断lock是否为null
        try (AutoReleaseLock keyLock = cache.tryLock("keyLock", 10, TimeUnit.SECONDS)) {
    
    
            if (keyLock != null) {
    
    
                System.out.println("lock");
            }
        }
        // 分布式锁操作, 上述操作的优化版本
        cache.tryLockAndRun("keyLock", 10,TimeUnit.SECONDS, () -> {
    
    
            System.out.println("aaa");
        });

        // umwrap 可以包装为原始类,进行缓存操作, 具体能转换为什么类型,请参考实现;注意泛型
        RedisStringCommands<byte[], byte[]> unwrap = cache.unwrap(RedisClusterCommands.class);

		
		// 分布中集群之间只有一个节点获取到锁执行,其他服务获取不到锁不再竞争,此时可以在reids中提供了set(k,v,nx,ex) 命令 可以实现锁操作 jetcache中使用
		cache.putIfAbsent(k, v) 
		
		//  自增等操作,jetcache暂时没做实现 可以使用unwrap 包装后使用
   RedisStringCommands<byte[], byte[]> unwrap = cache.unwrap(RedisClusterCommands.class);
  Long incr = unwrap.incr("key1".getBytes());
  
    }

The above is to use redis-lettuce in the springboot project, you can also use jedis, but redis-lettuce is still recommended

jetcache - jedis

Simply write it down, basically the same pom as redis-lettuce

  <dependency>
            <groupId>com.alicp.jetcache</groupId>
            <artifactId>jetcache-starter-redis</artifactId>
            <version>2.6.0</version>
        </dependency>

Configuration file
// The basic configuration is the same, jedis has one more pool configuration

jetcache:
  remote:
    default:
      type: redis
      keyConvertor: fastjson
      poolConfig:
        minIdle: 1
        maxIdle: 2
        maxTotal: 3
      host: 172.0.0.1
      port: 6379
  local:
    default:
      type: linkedhashmap

其他看 官网吧; springboot 环境下的jedis支持

以上是jetcache的简单使用,入手简单,若不是在springboot环境下 或者 使用原生的 请参照

Guess you like

Origin blog.csdn.net/xiaodujava/article/details/112506246