springboot 环境下 jetcache使用详解

jetcache

简介
github地址;jetcache 的优势在于比spring cache 提供更加强大的注解操作,并提供两级缓存,本地缓存和远端缓存(redis)以及异步cacheAPI操作,以及其他的TTL等

有些内容来源官网,本文仅供交流和学习

使用

springboot中使用

pom

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

配置文件

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

另外配置类上加注解

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

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

注解说明

注解 属性 说明
@cached 缓存数据 name 缓存实例的名称,可用作显示统计信息和作为key的前缀
area 缓存区域,默认为default
key 缓存key,使用spel表达式
expire 过期时间,如果未配置localExpire则本地缓存和remote缓存都使用此
localExpire 本地缓存过期时间
cacheType 缓存类型,可选EMOTE(远端), LOCAL(本地), BOTH(二级缓存)
localLimit 本地缓存最大数量
cacheNullValue 是否缓存null
serialPolicy 序列化方式,默认使用全局
condition 使用SpEL指定条件,如果表达式返回true的时候才去缓存中查询
@CacheUpdate 更新缓存 name 缓存实例的名称,可用作显示统计信息和作为key的前缀
area 缓存区域,默认default, 一般情况下不需要设置
name 同@cached.name,cache实例名
key 同@cached.key, 使用spel表达式指定
value 使用spel表达式指定缓存数据
condition 缓存条件,true更新缓存,false不更新缓存,使用spel指定
@CacheInvalidate 删除缓存 同@cacheUpdate一致 缓存无效,删除缓存时使用
@CachePenetrationProtect 缓存穿透保护,原理就是并发下加锁,超时时间内只有一个线程能执行,其他线程等待 value 默认 true, 是否开启
timeout 保护时间,默认integer最大值,其他线程等待超时时间,超时后执行方法
timeUnit 时间单位, 默认秒
@CacheRefresh 缓存刷新 refresh 刷新间隔
timeUnit 时间单位, 默认秒
stopRefreshAfterLastAccess 指定该key多长时间没有访问就停止刷新,如果不指定会一直刷新
refreshLockTimeout 类型为BOTH/REMOTE的缓存刷新时,同时只会有一台服务器在刷新,这台服务器会在远程缓存放置一个分布式锁,此配置指定该锁的超时时间,默认 锁超时时间为60s
@CreateCache ,标注在属性上创建缓存,并注入到spring中 同 @cached 略,详解同@cached

@cached
作用在方法上,类 必须为一个springbean, key 使用spel表达式

    @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
作用在方法上,类 必须为一个springbean, key 和value 使用spel表达式

   @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
添加缓存穿透保护 是jvm级别进程级别的的不是 分布式的;只保护本服务并发只有一个获取锁执行,其他等待

     @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
删除缓存

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

@createCache使用

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

常用api操作

// 直接在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());
  
    }

以上是在springboot项目中使用 redis-lettuce, 也可以使用 jedis ,不过还是推荐使用 redis-lettuce

jetcache - jedis

简单写下吧,基本上和redis-lettuce一致
pom

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

配置文件
// 基本配置也一样,jedis 多了一个 pool的配置

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环境下 或者 使用原生的 请参照

猜你喜欢

转载自blog.csdn.net/xiaodujava/article/details/112506246
今日推荐