SpringBoot緩存

緩存三問 ???

如果所有操作都是對數(shù)據(jù)庫進(jìn)行操作,那么勢必會對數(shù)據(jù)庫造成很大壓力,這時(shí)候如果把熱點(diǎn)放到緩存中是一個(gè)不錯(cuò)的選擇。緩存還可以進(jìn)行臨時(shí)數(shù)據(jù)的存放,比如短時(shí)驗(yàn)證碼之類的。

  • 如今流行的緩存技術(shù)?

    Redis、EhCache 2.x 、Generic、JCache (JSR-107)、Hazelcast、Infinispan、Guava、Simple

關(guān)于JSR-107標(biāo)準(zhǔn)

JSR-107

實(shí)例

pom.xml引入必要依賴

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

UserRepository.java

package com.inverseli.learning.domain;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

/**
 * @author liyuhao
 * @date 2018年9月30日上午10:07:12
 */
@CacheConfig(cacheNames = "Users") // 緩存在名為Users的對象中
public interface UserRepository extends JpaRepository<User,Long>{
    // 將該方法的返回值存入緩存中,并在查詢時(shí)先從緩沖中獲取,獲取不到,在到數(shù)據(jù)庫中進(jìn)行獲取
    @Cacheable 
    User findByName(String name);
    
    User findByNameAndAge(String name,Integer age);
    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);
}

注解詳解

@Cacheable: 將該方法的返回值存入緩存中,并在查詢時(shí)先從緩沖中獲取,獲取不到,在到數(shù)據(jù)庫中進(jìn)行獲取
@CachePut: 配置于函數(shù)上,能夠根據(jù)參數(shù)定義條件來進(jìn)行緩存,它與@Cacheable不同的是,它每次都會真是調(diào)用函數(shù),所以主要用于數(shù)據(jù)新增和修改操作上。意思就是說無論緩存中是否有數(shù)據(jù),我都要進(jìn)行方法執(zhí)行,進(jìn)行緩存中數(shù)據(jù)的更新。
@CacheEvict: 配置于函數(shù)上,通常用在刪除方法上,用來從緩存中移除相應(yīng)數(shù)據(jù)。除了同@Cacheable一樣的參數(shù)之外,它還有下面兩個(gè)參數(shù):
allEntries:非必需,默認(rèn)為false。當(dāng)為true時(shí),會移除所有數(shù)據(jù)
beforeInvocation:非必需,默認(rèn)為false,會在調(diào)用方法之后移除數(shù)據(jù)。當(dāng)為true時(shí),會在調(diào)用方法之前移除數(shù)據(jù)。

參考 - http://blog.didispace.com/springbootcache1/
完整實(shí)例 - https://github.com/Inverseli/SpringBoot-Learning/tree/master/learning4-4-1

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容