SpringCache使用案例詳解
1.新建測(cè)試項(xiàng)目SpringCache
引入依賴(lài)
<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í)體類(lèi)
@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è)試下沒(méi)問(wèn)題就搭建完成,開(kāi)始springcache的測(cè)試
2.SpringCache整合redis
下面是以redis為例,其他緩存也是下面這些步驟,一般來(lái)說(shuō)要把cache抽出成一個(gè)類(lèi),下面為了測(cè)試方便直接在controller里做
1.引入依賴(lài)
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.配置類(lèi)
@EnableCaching //開(kāi)啟緩存 @Configuration public class CacheConfig { @Bean public CacheManager redisCacheManager(RedisConnectionFactory factory) { // 配置序列化(解決亂碼的問(wèn)題),過(guò)期時(shí)間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() //過(guò)期時(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.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.訪(fǎng)問(wèn)http://localhost:8080/list測(cè)試,數(shù)據(jù)被緩存到redis中了
2.1.@Cacheable
@Cacheable:觸發(fā)緩存填充。
注解屬性
注解屬性 | 作用 |
---|---|
value / cacheNames | 用于指定緩存的名稱(chēng),可以指定一個(gè)或多個(gè)緩存名稱(chēng) |
key | 用于指定緩存的鍵,可以使用 SpEL 表達(dá)式 |
condition | 用于指定一個(gè)條件,如果條件成立,則執(zhí)行緩存 |
unless | 用于指定一個(gè)條件,如果條件不成立,則執(zhí)行緩存 |
keyGenerator | 用于指定自定義的緩存鍵生成器 |
cacheManager | 用于指定自定義的緩存管理器 |
sync | 用于指定是否使用同步模式,當(dāng)設(shè)置為 true 時(shí),表示在方法執(zhí)行時(shí),阻塞其他請(qǐng)求,直到緩存更新完成 |
SpEL上下文數(shù)據(jù)
屬性名稱(chēng) | 描述 | 示例 |
---|---|---|
methodName | 正在調(diào)用的方法的名稱(chēng) | #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"; }
訪(fǎng)問(wèn):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方法返回值不能寫(xiě)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:在類(lèi)級(jí)別共享一些常見(jiàn)的緩存相關(guān)設(shè)置。
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager") public class UserCache { }
3.SpringCache問(wèn)題
springCache的這些注解也受@Transactional的事務(wù)控制
@Transactional @Cacheable(value = "myCache", key = "#id") public String getCachedValueById(long id) { // 查詢(xún)底層數(shù)據(jù)源,如果緩存中沒(méi)有數(shù)據(jù) return fetchDataFromDataSource(id); }
@Cacheable 注解被用于方法 getCachedValueById 上,而該方法也被 @Transactional 注解標(biāo)記。這意味著當(dāng)方法被調(diào)用時(shí),緩存的操作和底層數(shù)據(jù)源的查詢(xún)將在同一個(gè)事務(wù)中進(jìn)行。如果事務(wù)回滾(例如,由于異常的發(fā)生),緩存的操作也會(huì)被回滾,確保數(shù)據(jù)的一致性。
springcache的讀模式和寫(xiě)模式什么意思,為什么說(shuō)springcache解決了讀模式的緩存擊穿,緩存穿透,緩存雪崩問(wèn)題,沒(méi)有解決寫(xiě)模式的這些問(wèn)題
讀模式和寫(xiě)模式是緩存中常用的兩種操作方式,分別涉及到對(duì)緩存的讀取和寫(xiě)入。
- 讀模式(Read-Through)
讀模式是指在讀取數(shù)據(jù)時(shí),首先嘗試從緩存中獲取數(shù)據(jù)。如果緩存中存在數(shù)據(jù),則直接返回緩存的值,避免了對(duì)底層數(shù)據(jù)源(例如數(shù)據(jù)庫(kù))的直接訪(fǎng)問(wèn)。如果緩存中不存在數(shù)據(jù),系統(tǒng)會(huì)查詢(xún)底層數(shù)據(jù)源,將查詢(xún)到的數(shù)據(jù)加載到緩存中,并返回給調(diào)用方。
Spring Cache 中的 @Cacheable 注解是典型的讀模式的代表。這樣的模式可以有效減輕對(duì)底層數(shù)據(jù)源的訪(fǎng)問(wèn)壓力,提高系統(tǒng)性能。
- 寫(xiě)模式(Write-Through)
寫(xiě)模式是指在對(duì)數(shù)據(jù)進(jìn)行寫(xiě)入或修改時(shí),首先對(duì)底層數(shù)據(jù)源進(jìn)行相應(yīng)的操作,然后再更新或清空緩存。這樣確保了緩存和底層數(shù)據(jù)源的一致性。
Spring Cache 中的 @CachePut 和 @CacheEvict 注解是寫(xiě)模式的代表。@CachePut 用于更新緩存,@CacheEvict 用于清除緩存。
關(guān)于 Spring Cache 解決問(wèn)題的說(shuō)法
關(guān)于 Spring Cache 解決了讀模式的緩存擊穿、緩存穿透、緩存雪崩問(wèn)題的說(shuō)法,主要是因?yàn)?Spring Cache 提供了對(duì)這些問(wèn)題的解決方案:
- 緩存擊穿: 通過(guò) @Cacheable 注解的 sync 屬性,可以控制是否使用同步模式,以避免在高并發(fā)情況下多個(gè)線(xiàn)程同時(shí)查詢(xún)緩存失效的情況。
- 緩存穿透: 通過(guò) @Cacheable 注解的 cache-null-values 屬性,可以緩存空值,防止對(duì)于一些不存在的 key,頻繁查詢(xún)底層數(shù)據(jù)源。
- 緩存雪崩: 通過(guò)設(shè)置緩存項(xiàng)的過(guò)期時(shí)間,以及使用隨機(jī)時(shí)間避免同時(shí)失效大量緩存項(xiàng),可以減緩緩存雪崩問(wèn)題的發(fā)生。
然而,寫(xiě)模式中可能存在一些問(wèn)題,比如緩存和底層數(shù)據(jù)源的一致性問(wèn)題,因?yàn)樵诟碌讓訑?shù)據(jù)源和更新緩存之間存在一定的時(shí)間差。Spring Cache 沒(méi)有提供對(duì)寫(xiě)模式問(wèn)題的直接解決方案。在一些對(duì)數(shù)據(jù)一致性要求較高的場(chǎng)景中,可能需要結(jié)合其他手段(如數(shù)據(jù)庫(kù)事務(wù)、消息隊(duì)列等)來(lái)保證寫(xiě)操作的一致性。
4.SpringCache實(shí)現(xiàn)多級(jí)緩存
到此這篇關(guān)于SpringCache使用詳解的文章就介紹到這了,更多相關(guān)SpringCache使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中wait與sleep的區(qū)別講解(wait有參及無(wú)參區(qū)別)
這篇文章主要介紹了Java中wait與sleep的講解(wait有參及無(wú)參區(qū)別),通過(guò)代碼介紹了wait()?與wait(?long?timeout?)?區(qū)別,wait(0)?與?sleep(0)區(qū)別,需要的朋友可以參考下2022-04-04java如何創(chuàng)建一個(gè)jdbc程序詳解
使用Java程序來(lái)操作數(shù)據(jù)庫(kù),后者更加直接的話(huà)就是使用Java程序來(lái)發(fā)送SQL語(yǔ)句的技術(shù)稱(chēng)之為:JDBC。下面這篇文章主要給大家介紹了關(guān)于利用java如何創(chuàng)建一個(gè)jdbc程序的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-11-11WebSocket無(wú)法注入屬性的問(wèn)題及解決方案
這篇文章主要介紹了WebSocket無(wú)法注入屬性的問(wèn)題及解決方法,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09IDEA集成JProfiler11可視化工具的詳細(xì)流程(安裝、集成、測(cè)試)
小編打算在IDEA中集成一下JProfiler11(現(xiàn)在有12版本了)工具,到網(wǎng)上搜都沒(méi)有找到合適的,于是自己動(dòng)手寫(xiě)個(gè),關(guān)于IDEA集成JProfiler11可視化工具(安裝、集成、測(cè)試)相關(guān)知識(shí)感興趣的朋友一起看看吧2021-06-06IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的全過(guò)程
Maven提供了大量不同類(lèi)型的Archetype模板,通過(guò)它們可以幫助用戶(hù)快速的創(chuàng)建Java項(xiàng)目,這篇文章主要給大家介紹了關(guān)于IDEA2023創(chuàng)建MavenWeb項(xiàng)目并搭建Servlet工程的相關(guān)資料,需要的朋友可以參考下2023-10-10Java如何獲取一個(gè)IP段內(nèi)的所有IP地址
這篇文章主要為大家詳細(xì)介紹了Java如何根據(jù)起始和結(jié)束的IP地址獲取IP段內(nèi)所有IP地址,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11Java 獲取網(wǎng)絡(luò)302重定向URL的方法
在本篇文章里小編給大家整理的是關(guān)于Java 獲取網(wǎng)絡(luò)302重定向URL的方法以及相關(guān)知識(shí)點(diǎn),有興趣的朋友們參考下。2019-08-08