Spring?Cache簡(jiǎn)單介紹和使用大全
一、簡(jiǎn)介
Spring Cache是一個(gè)框架,實(shí)現(xiàn)了基于注解的緩存功能,只需要簡(jiǎn)單地加一個(gè)注解,就能實(shí)現(xiàn)緩存功能。
Spring Cache提供了一層抽象,底層可以切換不同的cache實(shí)現(xiàn)。具體就是通過(guò)CacheManager接口來(lái)統(tǒng)一不同的緩存技術(shù)。
CacheManager是Spring提供的各種緩存技術(shù)抽象接口
針對(duì)不同的緩存技術(shù)需要實(shí)現(xiàn)不同的CacheManager:

CacheManager默認(rèn)使用的ConcurrentMapManager
Spring Cache 常用注解

在spring boot項(xiàng)目中,使用緩存技術(shù)只需在項(xiàng)目中導(dǎo)入相關(guān)緩存技術(shù)的依賴包,并在啟動(dòng)類上使用@EnableCaching開(kāi)啟緩存支持即可。
例如,使用Redis作為緩存技術(shù),只需要導(dǎo)入Spring data Redis的maven坐標(biāo)即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>spring cache的基本api在web下的context包中

如果有使用其他的api可以導(dǎo)入cache的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>二、使用默認(rèn)ConcurrentMapManager
(一)創(chuàng)建數(shù)據(jù)庫(kù)和表
創(chuàng)建cache_demo數(shù)據(jù)庫(kù),并創(chuàng)建user表
> create database cache_demo; Query OK, 1 row affected (0.02 sec) > use cache_demo; Database changed > create table user ( > id bigint primary key, > name varchar(50), > age int, > address varchar(50) >);

(二)創(chuàng)建boot項(xiàng)目
改POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.itheima</groupId>
<artifactId>cache_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.23</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.4.5</version>
</plugin>
</plugins>
</build>
</project>
寫(xiě)YML
server:
port: 8080
spring:
application:
#應(yīng)用的名稱,可選
name: cache_demo
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
mybatis-plus:
configuration:
#在映射實(shí)體或者屬性時(shí),將數(shù)據(jù)庫(kù)中表名和字段名中的下劃線去掉,按照駝峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_IDUser
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private int age;
private String address;
}
UserMapper
====================================================
@Mapper
public interface UserMapper extends BaseMapper<User>{
}
UserController
====================================================
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
// 增加User
@PostMapping
public User save(User user){
userService.save(user);
return user;
}
// 刪除User
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
// 更新User
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}
// 根據(jù)id查詢User
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}
// 根據(jù)id和name查詢User集合
@GetMapping("/list")
public List<User> list(User user){
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(user.getId() != null,User::getId,user.getId());
queryWrapper.eq(user.getName() != null,User::getName,user.getName());
List<User> list = userService.list(queryWrapper);
return list;
}
}
主啟動(dòng)類
@Slf4j
@SpringBootApplication
public class CacheDemoApplication {
public static void main(String[] args) {
SpringApplication.run(CacheDemoApplication.class,args);
log.info("項(xiàng)目啟動(dòng)成功...");
}
}(三)使用Api
1、@EnableCaching
啟動(dòng)類上加注解@EnableCaching // 使用spring cache
2、@CachePut
// 在controller中加入緩存對(duì)象
@Autowired
private CacheManager cacheManager;
/**
* CachePut:將方法返回值放入緩存
* value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
* key:緩存的key
*/
@CachePut(value = "userCache",key = "#user.id")
@PostMapping
public User save(User user){
userService.save(user);
return user;
}通過(guò)ctrl點(diǎn)進(jìn)key下載源碼后我們可以看到這里使用的是SpEL語(yǔ)言動(dòng)態(tài)獲取值

測(cè)試,使用 postman 發(fā)請(qǐng)求


第一次添加會(huì)將返回的user存放進(jìn)cacheManager中


3、@cacheable
在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒(méi)有數(shù)據(jù),調(diào)用方法并將方法返回值放到緩存中
/**
* Cacheable:在方法執(zhí)行前spring先查看緩存中是否有數(shù)據(jù),如果有數(shù)據(jù),則直接返回緩存數(shù)據(jù);若沒(méi)有數(shù)據(jù),調(diào)用方法并將方法返回值放到緩存中
* value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
* key:緩存的key
* condition:條件,滿足條件時(shí)才緩存數(shù)據(jù)
* unless:滿足條件則不緩存
*/
@Cacheable(value = "userCache",key = "#id",unless = "#result == null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
User user = userService.getById(id);
return user;
}測(cè)試,我們使用jack的id去查詢一下,同樣使用postman,在這個(gè)方法設(shè)置斷點(diǎn),如果沒(méi)有觸發(fā)斷點(diǎn)說(shuō)明是在cache中查詢直接返回的
4、@CacheEvict
/**
* CacheEvict:清理指定緩存
* value:緩存的名稱,每個(gè)緩存名稱下面可以有多個(gè)key
* key:緩存的key
*/
@CacheEvict(value = "userCache",key = "#p0")
//@CacheEvict(value = "userCache",key = "#root.args[0]")
//@CacheEvict(value = "userCache",key = "#id")
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
userService.removeById(id);
}
//@CacheEvict(value = "userCache",key = "#p0.id")
//@CacheEvict(value = "userCache",key = "#user.id")
//@CacheEvict(value = "userCache",key = "#root.args[0].id")
@CacheEvict(value = "userCache",key = "#result.id")
@PutMapping
public User update(User user){
userService.updateById(user);
return user;
}三、使用redis作為cache
導(dǎo)入redis依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>修改YML
server:
port: 8080
spring:
application:
#應(yīng)用的名稱,可選
name: cache_demo
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/cache_demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123456
redis:
host: 192.168.23.100
port: 6379
password: zjy123...000
database: 1
cache:
redis:
time-to-live: 1800000 #設(shè)置緩存過(guò)期時(shí)間,可選
mybatis-plus:
configuration:
#在映射實(shí)體或者屬性時(shí),將數(shù)據(jù)庫(kù)中表名和字段名中的下劃線去掉,按照駝峰命名法映射
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID啟動(dòng)項(xiàng)目后,cache變成了RedisCacheManager

使用postman發(fā)送save請(qǐng)求

db01

發(fā)送DELETE刪除緩存


到此這篇關(guān)于Spring Cache簡(jiǎn)單介紹和使用的文章就介紹到這了,更多相關(guān)Spring Cache使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
mybatis自動(dòng)建表的實(shí)現(xiàn)方法
這篇文章主要介紹了mybatis自動(dòng)建表的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
nacos使用占位符${}進(jìn)行參數(shù)配置的方法
這篇文章主要介紹了nacos如何使用占位符${}進(jìn)行參數(shù)配置,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12
MybatisPlus,無(wú)XML分分鐘實(shí)現(xiàn)CRUD操作
這篇文章主要介紹了MybatisPlus,無(wú)XML分分鐘實(shí)現(xiàn)CRUD操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08
Java?SpringBoot?獲取接口實(shí)現(xiàn)類匯總
這篇文章主要介紹了Java?SpringBoot?獲取接口實(shí)現(xiàn)類匯總,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09
Java實(shí)現(xiàn)word轉(zhuǎn)pdf并在關(guān)鍵字位置插入圖片
這篇文章主要為大家詳細(xì)介紹了如何利用Java實(shí)現(xiàn)word轉(zhuǎn)pdf,并在word中關(guān)鍵字位置插入圖片,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11

