緩存三問 笛园?恭理??
-
什么是緩存坡椒?
客戶端緩存
代理緩存
反向代理緩存
Web服務器端緩存
詳細參考:https://blog.csdn.net/xiao672585132/article/details/7178224 -
為什么要用緩存就缆?
如果所有操作都是對數據庫進行操作帖渠,那么勢必會對數據庫造成很大壓力,這時候如果把熱點放到緩存中是一個不錯的選擇竭宰。緩存還可以進行臨時數據的存放空郊,比如短時驗證碼之類的。
-
如今流行的緩存技術切揭?
Redis狞甚、EhCache 2.x 、Generic廓旬、JCache (JSR-107)哼审、Hazelcast、Infinispan孕豹、Guava涩盾、Simple
關于JSR-107標準
JSR-107
實例
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>{
// 將該方法的返回值存入緩存中,并在查詢時先從緩沖中獲取励背,獲取不到春霍,在到數據庫中進行獲取
@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: 將該方法的返回值存入緩存中,并在查詢時先從緩沖中獲取椅野,獲取不到终畅,在到數據庫中進行獲取
@CachePut: 配置于函數上籍胯,能夠根據參數定義條件來進行緩存竟闪,它與@Cacheable不同的是,它每次都會真是調用函數杖狼,所以主要用于數據新增和修改操作上炼蛤。意思就是說無論緩存中是否有數據,我都要進行方法執(zhí)行蝶涩,進行緩存中數據的更新理朋。
@CacheEvict: 配置于函數上,通常用在刪除方法上绿聘,用來從緩存中移除相應數據嗽上。除了同@Cacheable一樣的參數之外,它還有下面兩個參數:
allEntries:非必需熄攘,默認為false兽愤。當為true時,會移除所有數據
beforeInvocation:非必需,默認為false浅萧,會在調用方法之后移除數據逐沙。當為true時,會在調用方法之前移除數據洼畅。
參考 - http://blog.didispace.com/springbootcache1/
完整實例 - https://github.com/Inverseli/SpringBoot-Learning/tree/master/learning4-4-1