SpringCache使用案例詳解
1.新建測(cè)試項(xiàng)目SpringCache
引入依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--Mysql數(shù)據(jù)庫(kù)驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- MyBatis-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>實(shí)體類
@Data
public class User {
private Long id;
private String name;
private Integer age;
}mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl測(cè)試下沒問題就搭建完成,開始springcache的測(cè)試
2.SpringCache整合redis
下面是以redis為例,其他緩存也是下面這些步驟,一般來說要把cache抽出成一個(gè)類,下面為了測(cè)試方便直接在controller里做
1.引入依賴
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>2.配置類
@EnableCaching //開啟緩存
@Configuration
public class CacheConfig {
@Bean
public CacheManager redisCacheManager(RedisConnectionFactory factory) {
// 配置序列化(解決亂碼的問題),過期時(shí)間600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
//過期時(shí)間
.entryTtl(Duration.ofSeconds(600))
//緩存key
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
//緩存組件value
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
//value不為空,為空?qǐng)?bào)錯(cuò)
.disableCachingNullValues()
.computePrefixWith(cacheName -> cacheName + ":");
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}3.application.yml
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
redis:
host: 127.0.0.1
port: 6379
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl4.controller
@RestController
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager")
public class UserController {
@Autowired
UserMapper userMapper;
@GetMapping("/list")
@Cacheable(key = "#root.method.name")
public List<User> list() {
return userMapper.selectList(null);
}
}
@RestController
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager")
public class UserController {
@Autowired
UserMapper userMapper;
@GetMapping("/list")
@Cacheable(key = "#root.method.name")
public List<User> list() {
return userMapper.selectList(null);
}
}5.訪問http://localhost:8080/list測(cè)試,數(shù)據(jù)被緩存到redis中了
2.1.@Cacheable
@Cacheable:觸發(fā)緩存填充。
注解屬性
| 注解屬性 | 作用 |
|---|---|
| value / cacheNames | 用于指定緩存的名稱,可以指定一個(gè)或多個(gè)緩存名稱 |
| key | 用于指定緩存的鍵,可以使用 SpEL 表達(dá)式 |
| condition | 用于指定一個(gè)條件,如果條件成立,則執(zhí)行緩存 |
| unless | 用于指定一個(gè)條件,如果條件不成立,則執(zhí)行緩存 |
| keyGenerator | 用于指定自定義的緩存鍵生成器 |
| cacheManager | 用于指定自定義的緩存管理器 |
| sync | 用于指定是否使用同步模式,當(dāng)設(shè)置為 true 時(shí),表示在方法執(zhí)行時(shí),阻塞其他請(qǐng)求,直到緩存更新完成 |
SpEL上下文數(shù)據(jù)
| 屬性名稱 | 描述 | 示例 |
|---|---|---|
| methodName | 正在調(diào)用的方法的名稱 | #root.methodName |
| method | 正在調(diào)用的方法 | #root.method.name |
| target | 正在調(diào)用的目標(biāo)對(duì)象 | #root.target |
| targetClass | 被調(diào)用目標(biāo)的class | #root.targetClass |
| args | 用于調(diào)用目標(biāo)的參數(shù) | #root.args[0] |
| caches | 當(dāng)前被調(diào)用的方法使用的Cache | #root.caches[0].name |
| result | 方法調(diào)用的結(jié)果 | #result |
/**
* 生成的緩存:myCache:qwer value:"9999"
* condition = "#param.length() > 3" 參數(shù)長(zhǎng)度大于3進(jìn)行緩存
* unless = "#result == null" 結(jié)果等于null不進(jìn)行緩存
*/
@GetMapping("/getCachedValue")
@Cacheable(value = "myCache", key = "#param", condition = "#param.length() > 3", unless = "#result == null")
public String getCachedValue(@RequestParam("param") String param) {
return "9999";
}訪問:http://localhost:8080/getCachedValue?param=qwer測(cè)試,成功緩存,修改代碼return null;再測(cè)試,就不會(huì)進(jìn)行緩存
/**
* 可以緩存null值,但會(huì)亂碼,不影響使用
* 緩存null值有兩種情況:
* 1.return null;
* 2.方法返回值為void
*/
@GetMapping("/getUser")
@Cacheable(key = "#uid")
public User getUser(@RequestParam("uid") Long uid) {
return userMapper.selectById(uid);
}
2.2.@CacheEvict
@CacheEvict:觸發(fā)緩存逐出。
@GetMapping("/cacheEvict")
@CacheEvict(key = "'list'")//清除鍵為key的緩存
public void cacheEvict(){
}
@GetMapping("/cacheEvictAll")
@CacheEvict(key = "'user'", allEntries = true)//清除user分區(qū)下的所有緩存
public void cacheEvictAll() {
}2.3.@Cacheput
@CachePut:在不干擾方法執(zhí)行的情況下更新緩存。
@GetMapping("/getUser")
@Cacheable(key = "#uid")
public User getUser(@RequestParam("uid") Long uid) {
return userMapper.selectById(uid);
}
@GetMapping("/update")
@CachePut(key = "#uid")
public User update(@RequestParam("uid") Long uid) {
User user = new User();
user.setId(uid);
user.setName("lisi9999");
userMapper.updateById(user);
return user;
}1.先http://localhost:8080/getUser?uid=2進(jìn)行緩存
2.再http://localhost:8080/update?uid=2刷新緩存
3.再http://localhost:8080/getUser?uid=2查緩存
可以看到緩存被正確更新
注意:update方法返回值不能寫void,否則會(huì)觸發(fā)緩存空值的情況,緩存被刷新成亂碼了
2.4.@Caching
@Caching:重新組合要應(yīng)用于方法的多個(gè)緩存操作。
/**
* @Cacheable(key = "'allBooks'"):表示方法的返回值應(yīng)該被緩存,使用 allBooks 作為緩存的鍵。
* @CacheEvict(key = "#isbn"):表示在調(diào)用這個(gè)方法時(shí),會(huì)清除緩存中鍵為 #isbn 的緩存項(xiàng)。
* @CacheEvict(key = "'popularBooks'"):表示在調(diào)用這個(gè)方法時(shí),會(huì)清除緩存中鍵為 'popularBooks' 的緩存項(xiàng)。
*/
@Caching(
cacheable = @Cacheable(key = "'allBooks'"),
evict = {
@CacheEvict(key = "#isbn"),
@CacheEvict(key = "'popularBooks'")
}
)
public String updateBookByIsbn(String isbn, String newTitle) {
System.out.println("Updating book in the database for ISBN: " + isbn);
// Simulate updating data in a database
return newTitle;
}2.5.@CacheConfig
@CacheConfig:在類級(jí)別共享一些常見的緩存相關(guān)設(shè)置。
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager")
public class UserCache {
}3.SpringCache問題
springCache的這些注解也受@Transactional的事務(wù)控制
@Transactional
@Cacheable(value = "myCache", key = "#id")
public String getCachedValueById(long id) {
// 查詢底層數(shù)據(jù)源,如果緩存中沒有數(shù)據(jù)
return fetchDataFromDataSource(id);
}@Cacheable 注解被用于方法 getCachedValueById 上,而該方法也被 @Transactional 注解標(biāo)記。這意味著當(dāng)方法被調(diào)用時(shí),緩存的操作和底層數(shù)據(jù)源的查詢將在同一個(gè)事務(wù)中進(jìn)行。如果事務(wù)回滾(例如,由于異常的發(fā)生),緩存的操作也會(huì)被回滾,確保數(shù)據(jù)的一致性。
springcache的讀模式和寫模式什么意思,為什么說springcache解決了讀模式的緩存擊穿,緩存穿透,緩存雪崩問題,沒有解決寫模式的這些問題
讀模式和寫模式是緩存中常用的兩種操作方式,分別涉及到對(duì)緩存的讀取和寫入。
- 讀模式(Read-Through)
讀模式是指在讀取數(shù)據(jù)時(shí),首先嘗試從緩存中獲取數(shù)據(jù)。如果緩存中存在數(shù)據(jù),則直接返回緩存的值,避免了對(duì)底層數(shù)據(jù)源(例如數(shù)據(jù)庫(kù))的直接訪問。如果緩存中不存在數(shù)據(jù),系統(tǒng)會(huì)查詢底層數(shù)據(jù)源,將查詢到的數(shù)據(jù)加載到緩存中,并返回給調(diào)用方。
Spring Cache 中的 @Cacheable 注解是典型的讀模式的代表。這樣的模式可以有效減輕對(duì)底層數(shù)據(jù)源的訪問壓力,提高系統(tǒng)性能。
- 寫模式(Write-Through)
寫模式是指在對(duì)數(shù)據(jù)進(jìn)行寫入或修改時(shí),首先對(duì)底層數(shù)據(jù)源進(jìn)行相應(yīng)的操作,然后再更新或清空緩存。這樣確保了緩存和底層數(shù)據(jù)源的一致性。
Spring Cache 中的 @CachePut 和 @CacheEvict 注解是寫模式的代表。@CachePut 用于更新緩存,@CacheEvict 用于清除緩存。
關(guān)于 Spring Cache 解決問題的說法
關(guān)于 Spring Cache 解決了讀模式的緩存擊穿、緩存穿透、緩存雪崩問題的說法,主要是因?yàn)?Spring Cache 提供了對(duì)這些問題的解決方案:
- 緩存擊穿: 通過 @Cacheable 注解的 sync 屬性,可以控制是否使用同步模式,以避免在高并發(fā)情況下多個(gè)線程同時(shí)查詢緩存失效的情況。
- 緩存穿透: 通過 @Cacheable 注解的 cache-null-values 屬性,可以緩存空值,防止對(duì)于一些不存在的 key,頻繁查詢底層數(shù)據(jù)源。
- 緩存雪崩: 通過設(shè)置緩存項(xiàng)的過期時(shí)間,以及使用隨機(jī)時(shí)間避免同時(shí)失效大量緩存項(xiàng),可以減緩緩存雪崩問題的發(fā)生。
然而,寫模式中可能存在一些問題,比如緩存和底層數(shù)據(jù)源的一致性問題,因?yàn)樵诟碌讓訑?shù)據(jù)源和更新緩存之間存在一定的時(shí)間差。Spring Cache 沒有提供對(duì)寫模式問題的直接解決方案。在一些對(duì)數(shù)據(jù)一致性要求較高的場(chǎng)景中,可能需要結(jié)合其他手段(如數(shù)據(jù)庫(kù)事務(wù)、消息隊(duì)列等)來保證寫操作的一致性。
4.SpringCache實(shí)現(xiàn)多級(jí)緩存
到此這篇關(guān)于SpringCache使用詳解的文章就介紹到這了,更多相關(guān)SpringCache使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMVC RESTful支持實(shí)現(xiàn)過程演示
這篇文章主要介紹了SpringMVC RESTful支持實(shí)現(xiàn)過程演示,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
SpringBoot返回結(jié)果統(tǒng)一處理實(shí)例詳解
這篇文章主要為大家介紹了SpringBoot返回結(jié)果統(tǒng)一處理實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
SpringBoot實(shí)現(xiàn)接口防抖的實(shí)戰(zhàn)方案大全
這篇文章主要介紹了四種在SpringBoot中實(shí)現(xiàn)接口防抖的方案,包括前端防抖+后端令牌鎖、數(shù)據(jù)庫(kù)唯一約束、本地Guava緩存和Token令牌機(jī)制,每種方案都有其優(yōu)缺點(diǎn),選擇時(shí)應(yīng)根據(jù)業(yè)務(wù)重要性和系統(tǒng)架構(gòu)來決定,需要的朋友可以參考下2025-12-12
Spring?Cache+Redis緩存數(shù)據(jù)的實(shí)現(xiàn)示例
本文主要介紹了Spring?Cache+Redis緩存數(shù)據(jù),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
關(guān)于Java?CPU或內(nèi)存使用率過高問題定位
Spring?cloud微服務(wù)廣泛應(yīng)用后,服務(wù)的監(jiān)控和運(yùn)維壓力也與日俱增,經(jīng)常有服務(wù)出現(xiàn)CPU或者內(nèi)存使用率過高的告警,那么遇到這樣的問題我們?cè)撊绾闻挪槟兀课覀兛梢越柚男┕ぞ邅矶ㄎ粏栴}呢?本文將介紹一下遇到此類問題的解決思路和方法2024-10-10
BeanUtils.copyProperties復(fù)制不生效的解決
這篇文章主要介紹了BeanUtils.copyProperties復(fù)制不生效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09

