Spring Boot 2.1.4整合JetCache緩存框架實現本地caffeine遠程redis存儲(一、使用Lettuce)

JetCache是一個阿里巴巴開源的基於Java的緩存系統封裝,提供統一的API和註解來簡化緩存的使用,SpringBoot2.1.4截止到當前爲止,Maven倉庫發佈的整合JetCache的版本爲2.6.0.M1,JetCache提供了 本地緩存LinkedHashMapCache和CaffeineCache( 一個高性能的 Java 緩存庫)兩種,遠程可以支持Tair,Redis,今天我們就來選擇使用 Caffeine和Redis進行整合來實現二級緩存.

首先要引入依賴,

Caffeine是Spring Boot 2取代Guava,內置的本地緩存

<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

Redis是遠程緩存,Redis比較常用的客戶端有Jedis,Lettuce,Redisson,Spring Boot 2不再推薦使用Jedis作爲redis的緩存客戶端,而默認採用lettuce作爲默認客戶端,當然還有Redisson,但是由於JetCache不支持Redisson,只支持jedis和letture.所以我們只能選擇這兩個。JetCache的官方文檔比較常用的示例都是用的Jedis或者使用的Redis哨兵集羣模式,如果你的Redis是單點服務器,那麼使用jedis也可以。這裏我們拿Lettuce作爲客戶端舉例,Redis則是採用的是Cluster集羣模式。

<!-- https://mvnrepository.com/artifact/com.alicp.jetcache/jetcache-starter-redis-lettuce -->
<dependency>
    <groupId>com.alicp.jetcache</groupId>
	<artifactId>jetcache-starter-redis-lettuce</artifactId>
	<version>2.6.0.M1</version>
</dependency>

版本爲最新的2.6.0.M1,因爲JetCache 2.3以上版本才支持Lettuce,

同時還要引入Redis的依賴

<!-- 添加對redis的支持 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- 添加對連接池的支持 -->
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
</dependency>

application.yml文件中要配置相關配置,有一點JetCache做的不好,就是yml下jetcache沒有代碼提示

jetcache:
  statIntervalMinutes: 1 #統計間隔
  areaInCacheName: false
  local:
    default: #默認area
      type: caffeine
      keyConvertor: fastjson
  remote:
    default:
      type: redis.lettuce #使用lettuce
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 1
        maxIdle: 50
        maxTotal: 1000
        maxWait: 1000  
#     uri: ['redis://[email protected]:6379/0','redis://[email protected]:6379/0','redis://[email protected]:6379/0']
      uri:
        - redis://[email protected]:6379/0  #redis://密碼@IP:端口/庫
        - redis://[email protected]:6379/0
        - redis://[email protected]:6379/0
      readFrom: masterPreferred #master優先

JetCache還內置了統計功能,statIntervalMinutes爲統計間隔時間,這些基本配置可以從git上wiki獲取。

如果除了使用JetCache註解的方式使用緩存以外,如果你還需要通過使用StringRedisTemplate或者RedisTemplate的方式使用Reids,那麼還需要配置,Spring Boot 2默認也是是要弄個lettuce來作爲java客戶端連接的

spring:
  redis:
    cluster:
      nodes: 
        - 192.168.14.231:6379
        - 192.168.14.232:6379
        - 192.168.14.233:6379
    password: password
    lettuce:
      pool:
        min-idle: 5
        max-idle: 50
        max-active: 100
        max-wait: 1000

然後還要在Application.java啓動文件中添加註解、com.xxxx爲自己的項目包名

@SpringBootApplication
@EnableMethodCache(basePackages = { "com.xxxx" })
@EnableCreateCacheAnnotation
public class Application {

}

如何通過JetCache的註解使用

@RestController
public class UserController {

    // 定義一個是String類型的遠程緩存
    @CreateCache(name ="i5xforyou.username", expire = 120, cacheType = CacheType.REMOTE)
    private Cache<String, String> userNameCache;
    // 定義一個是User對象的二級緩存(本地+遠程)
    @CreateCache(name ="i5xforyou.user", localExpire = 60, localLimit = 100, expire = 120, cacheType = CacheType.BOTH)
    private Cache<String, User> userCache;


    
    @GetMapping(value = "/getUser")
    public String getUserInfo() {
            
            userNameCache.put("123", "userName");
            System.out.println("userNameCache : " + userNameCache.get("123"));
            
            User user = new User();
            user.setUserName("user.userName");
            userCache.put("1234", user);
            System.out.println("userCache: " + userCache.get("1234").geUserName());

            return "";
        
    }
    
}

這裏有一點要特別注意的: 就是User一定要 implements Serializable 進行序列化,否則userCache.get("1234")將會取出來一個null對象,因爲無法存進Redis緩存內。

通過以上的配置,就可以使用JetCache註解的方式來使用緩存了。其他用法還可以繼續關注https://github.com/alibaba/jetcache 來學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章