1. 程式人生 > 其它 >Spring Cache快取

Spring Cache快取

技術標籤:資料庫redis

為什麼要用springcache?它解決了什麼問題?

springcache 是spring3.1版本釋出出來的,他是對使用快取進行封裝和抽象,通過在方法上使用annotation註解就能拿到快取結果。正時因為用來annotation,所以它解決了業務程式碼和快取程式碼的耦合度問題,即再不侵入業務程式碼的基礎上讓現有程式碼即刻支援快取,它讓開發人員無感知的使用了快取。

特別注意:(注意:對於redis的快取,springcache只支援string)

使用步驟:

  1. pom檔案加入依賴包

    1.  <!--redis-->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-data-redis</artifactId>
              </dependency>
              <!--spring cache-->
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-cache</artifactId>
              </dependency>
              <!--spring cache連線池依賴包-->
              <dependency>
                  <groupId>org.apache.commons</groupId>
                  <artifactId>commons-pool2</artifactId>
              </dependency>

  2. 配置檔案加入redis配置資訊

    1. #redis配置
      spring:
        redis:
          database: 0
          host: 192.168.2.256
          port: 6379
          password:
          lettuce:
            pool:
              #連線池最大連線數
              max-active: 8
              #連線池中最大阻塞等待時間
              max-wait: -1ms
              #連線池中的最大空閒連線
              max-idle: 8
              #連線池中的最小空閒連線
              min-idle: 0
          #連線超時時間
          timeout: 5000ms

  3. 開啟快取配置,設定序列化

常用註解

@CacheConfig

@CacheConfig是類級別的註解,統一該類的所有快取可以字首

例:@CacheConfig(cacheNames={"user"})

public class UserService{ ....}

以上程式碼,代表了該類的所有快取可以都是“user::”為字首

@Cacheable

@Cacheable是方法級別的註解,用於將方法的結果快取起來

例:@Cacheable(key="#id")

public User findUserById(Integer id){....}

以上方法被呼叫時,先從快取中讀取資料,如果快取沒有找到資料,再執行方法體,最後把返回值新增到快取中

注意:@Cacheable 一般是配合@CacheConfig一起使用的

例如:上文的@CacheConfig(cacheNames={"user"})和@Cacheable({key="#id"})一起使用時,呼叫方法傳入id=100,那redis對應的key=user::100,value通過採用GenericJackson2JsonRedisSerializer序列化為json

@CahcePut

@CahcePut是方法級別的註解,用於更新快取

例:@CachePut(key="#obj.id")

public User updateUser(User obj){

this.UserMapper.UpdateByPrimarySelective(obj);

return this.userMapper.selectByPrimaryKey(obj.getId());

}

以上方法被呼叫時,先執行方法體,然後springcache通過返回更新快取,即key="#obj.id",value=User

@CacheEvict(key="#id")

@CachePut是方法級別的註解,用於刪除快取

springcache的大坑

  1. 對於redis的快取,springcache只支援String,其他的Hash、List、set、ZSet都不支援,所以對於Hash、List、set、ZSet只能用RedisTemplate
  2. 對於多表查詢的資料快取,springcache是用支援的,只支援單表的簡單快取。對於多表的整體快取,只能用RedisTemplate。