SpringCache使用案例詳解
1.新建測試項目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ù)庫驅(qū)動--> <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>
實體類
@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
測試下沒問題就搭建完成,開始springcache的測試
2.SpringCache整合redis
下面是以redis為例,其他緩存也是下面這些步驟,一般來說要把cache抽出成一個類,下面為了測試方便直接在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) { // 配置序列化(解決亂碼的問題),過期時間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //過期時間 .entryTtl(Duration.ofSeconds(600)) //緩存key .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) //緩存組件value .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())) //value不為空,為空報錯 .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.StdOutImpl
4.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測試,數(shù)據(jù)被緩存到redis中了
2.1.@Cacheable
@Cacheable:觸發(fā)緩存填充。
注解屬性
注解屬性 | 作用 |
---|---|
value / cacheNames | 用于指定緩存的名稱,可以指定一個或多個緩存名稱 |
key | 用于指定緩存的鍵,可以使用 SpEL 表達式 |
condition | 用于指定一個條件,如果條件成立,則執(zhí)行緩存 |
unless | 用于指定一個條件,如果條件不成立,則執(zhí)行緩存 |
keyGenerator | 用于指定自定義的緩存鍵生成器 |
cacheManager | 用于指定自定義的緩存管理器 |
sync | 用于指定是否使用同步模式,當設(shè)置為 true 時,表示在方法執(zhí)行時,阻塞其他請求,直到緩存更新完成 |
SpEL上下文數(shù)據(jù)
屬性名稱 | 描述 | 示例 |
---|---|---|
methodName | 正在調(diào)用的方法的名稱 | #root.methodName |
method | 正在調(diào)用的方法 | #root.method.name |
target | 正在調(diào)用的目標對象 | #root.target |
targetClass | 被調(diào)用目標的class | #root.targetClass |
args | 用于調(diào)用目標的參數(shù) | #root.args[0] |
caches | 當前被調(diào)用的方法使用的Cache | #root.caches[0].name |
result | 方法調(diào)用的結(jié)果 | #result |
/** * 生成的緩存:myCache:qwer value:"9999" * condition = "#param.length() > 3" 參數(shù)長度大于3進行緩存 * unless = "#result == null" 結(jié)果等于null不進行緩存 */ @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測試,成功緩存,修改代碼return null;再測試,就不會進行緩存
/** * 可以緩存null值,但會亂碼,不影響使用 * 緩存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進行緩存
2.再http://localhost:8080/update?uid=2刷新緩存
3.再http://localhost:8080/getUser?uid=2查緩存
可以看到緩存被正確更新
注意:update方法返回值不能寫void,否則會觸發(fā)緩存空值的情況,緩存被刷新成亂碼了
2.4.@Caching
@Caching:重新組合要應用于方法的多個緩存操作。
/** * @Cacheable(key = "'allBooks'"):表示方法的返回值應該被緩存,使用 allBooks 作為緩存的鍵。 * @CacheEvict(key = "#isbn"):表示在調(diào)用這個方法時,會清除緩存中鍵為 #isbn 的緩存項。 * @CacheEvict(key = "'popularBooks'"):表示在調(diào)用這個方法時,會清除緩存中鍵為 'popularBooks' 的緩存項。 */ @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:在類級別共享一些常見的緩存相關(guān)設(shè)置。
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager") public class UserCache { }
3.SpringCache問題
springCache的這些注解也受@Transactional的事務控制
@Transactional @Cacheable(value = "myCache", key = "#id") public String getCachedValueById(long id) { // 查詢底層數(shù)據(jù)源,如果緩存中沒有數(shù)據(jù) return fetchDataFromDataSource(id); }
@Cacheable 注解被用于方法 getCachedValueById 上,而該方法也被 @Transactional 注解標記。這意味著當方法被調(diào)用時,緩存的操作和底層數(shù)據(jù)源的查詢將在同一個事務中進行。如果事務回滾(例如,由于異常的發(fā)生),緩存的操作也會被回滾,確保數(shù)據(jù)的一致性。
springcache的讀模式和寫模式什么意思,為什么說springcache解決了讀模式的緩存擊穿,緩存穿透,緩存雪崩問題,沒有解決寫模式的這些問題
讀模式和寫模式是緩存中常用的兩種操作方式,分別涉及到對緩存的讀取和寫入。
- 讀模式(Read-Through)
讀模式是指在讀取數(shù)據(jù)時,首先嘗試從緩存中獲取數(shù)據(jù)。如果緩存中存在數(shù)據(jù),則直接返回緩存的值,避免了對底層數(shù)據(jù)源(例如數(shù)據(jù)庫)的直接訪問。如果緩存中不存在數(shù)據(jù),系統(tǒng)會查詢底層數(shù)據(jù)源,將查詢到的數(shù)據(jù)加載到緩存中,并返回給調(diào)用方。
Spring Cache 中的 @Cacheable 注解是典型的讀模式的代表。這樣的模式可以有效減輕對底層數(shù)據(jù)源的訪問壓力,提高系統(tǒng)性能。
- 寫模式(Write-Through)
寫模式是指在對數(shù)據(jù)進行寫入或修改時,首先對底層數(shù)據(jù)源進行相應的操作,然后再更新或清空緩存。這樣確保了緩存和底層數(shù)據(jù)源的一致性。
Spring Cache 中的 @CachePut 和 @CacheEvict 注解是寫模式的代表。@CachePut 用于更新緩存,@CacheEvict 用于清除緩存。
關(guān)于 Spring Cache 解決問題的說法
關(guān)于 Spring Cache 解決了讀模式的緩存擊穿、緩存穿透、緩存雪崩問題的說法,主要是因為 Spring Cache 提供了對這些問題的解決方案:
- 緩存擊穿: 通過 @Cacheable 注解的 sync 屬性,可以控制是否使用同步模式,以避免在高并發(fā)情況下多個線程同時查詢緩存失效的情況。
- 緩存穿透: 通過 @Cacheable 注解的 cache-null-values 屬性,可以緩存空值,防止對于一些不存在的 key,頻繁查詢底層數(shù)據(jù)源。
- 緩存雪崩: 通過設(shè)置緩存項的過期時間,以及使用隨機時間避免同時失效大量緩存項,可以減緩緩存雪崩問題的發(fā)生。
然而,寫模式中可能存在一些問題,比如緩存和底層數(shù)據(jù)源的一致性問題,因為在更新底層數(shù)據(jù)源和更新緩存之間存在一定的時間差。Spring Cache 沒有提供對寫模式問題的直接解決方案。在一些對數(shù)據(jù)一致性要求較高的場景中,可能需要結(jié)合其他手段(如數(shù)據(jù)庫事務、消息隊列等)來保證寫操作的一致性。
4.SpringCache實現(xiàn)多級緩存
到此這篇關(guān)于SpringCache使用詳解的文章就介紹到這了,更多相關(guān)SpringCache使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中wait與sleep的區(qū)別講解(wait有參及無參區(qū)別)
這篇文章主要介紹了Java中wait與sleep的講解(wait有參及無參區(qū)別),通過代碼介紹了wait()?與wait(?long?timeout?)?區(qū)別,wait(0)?與?sleep(0)區(qū)別,需要的朋友可以參考下2022-04-04IDEA集成JProfiler11可視化工具的詳細流程(安裝、集成、測試)
小編打算在IDEA中集成一下JProfiler11(現(xiàn)在有12版本了)工具,到網(wǎng)上搜都沒有找到合適的,于是自己動手寫個,關(guān)于IDEA集成JProfiler11可視化工具(安裝、集成、測試)相關(guān)知識感興趣的朋友一起看看吧2021-06-06IDEA2023創(chuàng)建MavenWeb項目并搭建Servlet工程的全過程
Maven提供了大量不同類型的Archetype模板,通過它們可以幫助用戶快速的創(chuàng)建Java項目,這篇文章主要給大家介紹了關(guān)于IDEA2023創(chuàng)建MavenWeb項目并搭建Servlet工程的相關(guān)資料,需要的朋友可以參考下2023-10-10Java 獲取網(wǎng)絡(luò)302重定向URL的方法
在本篇文章里小編給大家整理的是關(guān)于Java 獲取網(wǎng)絡(luò)302重定向URL的方法以及相關(guān)知識點,有興趣的朋友們參考下。2019-08-08