緩存三問 ???
-
什么是緩存?
客戶端緩存
代理緩存
反向代理緩存
Web服務(wù)器端緩存
詳細(xì)參考:https://blog.csdn.net/xiao672585132/article/details/7178224 -
為什么要用緩存?
如果所有操作都是對數(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)

實(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