SpringCache
- 1.新建測試項目SpringCache
- 2.SpringCache整合redis
- 2.1.@Cacheable
- 2.2.@CacheEvict
- 2.3.@Cacheput
- 2.4.@Caching
- 2.5.@CacheConfig
- 3.SpringCache問題
- 4.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數據庫驅動--><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/Shanghaiusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
測試下沒問題就搭建完成,開始springcache的測試
2.SpringCache整合redis
spring cache官方文檔
spEl語法說明官方文檔
下面是以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 {@Beanpublic 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/Shanghaiusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverredis:host: 127.0.0.1port: 6379password: 123456
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4.controller
@RestController
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager")
public class UserController {@AutowiredUserMapper userMapper;@GetMapping("/list")@Cacheable(key = "#root.method.name")public List<User> list() {return userMapper.selectList(null);}
}
5.訪問http://localhost:8080/list測試,數據被緩存到redis中了
2.1.@Cacheable
@Cacheable:觸發緩存填充。
注解屬性
注解屬性 | 作用 |
---|---|
value / cacheNames | 用于指定緩存的名稱,可以指定一個或多個緩存名稱 |
key | 用于指定緩存的鍵,可以使用 SpEL 表達式 |
condition | 用于指定一個條件,如果條件成立,則執行緩存 |
unless | 用于指定一個條件,如果條件不成立,則執行緩存 |
keyGenerator | 用于指定自定義的緩存鍵生成器 |
cacheManager | 用于指定自定義的緩存管理器 |
sync | 用于指定是否使用同步模式,當設置為 true 時,表示在方法執行時,阻塞其他請求,直到緩存更新完成 |
SpEL上下文數據
屬性名稱 | 描述 | 示例 |
---|---|---|
methodName | 正在調用的方法的名稱 | #root.methodName |
method | 正在調用的方法 | #root.method.name |
target | 正在調用的目標對象 | #root.target |
targetClass | 被調用目標的class | #root.targetClass |
args | 用于調用目標的參數 | #root.args[0] |
caches | 當前被調用的方法使用的Cache | #root.caches[0].name |
result | 方法調用的結果 | #result |
/*** 生成的緩存:myCache:qwer value:"9999"* condition = "#param.length() > 3" 參數長度大于3進行緩存* unless = "#result == null" 結果等于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:觸發緩存逐出。
@GetMapping("/cacheEvict")
@CacheEvict(key = "'list'")//清除鍵為key的緩存
public void cacheEvict(){
}@GetMapping("/cacheEvictAll")
@CacheEvict(key = "'user'", allEntries = true)//清除user分區下的所有緩存
public void cacheEvictAll() {
}
2.3.@Cacheput
@CachePut:在不干擾方法執行的情況下更新緩存。
@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,否則會觸發緩存空值的情況,緩存被刷新成亂碼了
2.4.@Caching
@Caching:重新組合要應用于方法的多個緩存操作。
/*** @Cacheable(key = "'allBooks'"):表示方法的返回值應該被緩存,使用 allBooks 作為緩存的鍵。* @CacheEvict(key = "#isbn"):表示在調用這個方法時,會清除緩存中鍵為 #isbn 的緩存項。* @CacheEvict(key = "'popularBooks'"):表示在調用這個方法時,會清除緩存中鍵為 '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 databasereturn newTitle;
}
2.5.@CacheConfig
@CacheConfig:在類級別共享一些常見的緩存相關設置。
@CacheConfig(cacheNames = "user", cacheManager = "redisCacheManager")
public class UserCache {}
3.SpringCache問題
springCache的這些注解也受@Transactional的事務控制
@Transactional
@Cacheable(value = "myCache", key = "#id")
public String getCachedValueById(long id) {// 查詢底層數據源,如果緩存中沒有數據return fetchDataFromDataSource(id);
}
@Cacheable 注解被用于方法 getCachedValueById 上,而該方法也被 @Transactional 注解標記。這意味著當方法被調用時,緩存的操作和底層數據源的查詢將在同一個事務中進行。如果事務回滾(例如,由于異常的發生),緩存的操作也會被回滾,確保數據的一致性。
springcache的讀模式和寫模式什么意思,為什么說springcache解決了讀模式的緩存擊穿,緩存穿透,緩存雪崩問題,沒有解決寫模式的這些問題
讀模式和寫模式是緩存中常用的兩種操作方式,分別涉及到對緩存的讀取和寫入。
- 讀模式(Read-Through)
讀模式是指在讀取數據時,首先嘗試從緩存中獲取數據。如果緩存中存在數據,則直接返回緩存的值,避免了對底層數據源(例如數據庫)的直接訪問。如果緩存中不存在數據,系統會查詢底層數據源,將查詢到的數據加載到緩存中,并返回給調用方。
Spring Cache 中的 @Cacheable 注解是典型的讀模式的代表。這樣的模式可以有效減輕對底層數據源的訪問壓力,提高系統性能。
- 寫模式(Write-Through)
寫模式是指在對數據進行寫入或修改時,首先對底層數據源進行相應的操作,然后再更新或清空緩存。這樣確保了緩存和底層數據源的一致性。
Spring Cache 中的 @CachePut 和 @CacheEvict 注解是寫模式的代表。@CachePut 用于更新緩存,@CacheEvict 用于清除緩存。
關于 Spring Cache 解決問題的說法
關于 Spring Cache 解決了讀模式的緩存擊穿、緩存穿透、緩存雪崩問題的說法,主要是因為 Spring Cache 提供了對這些問題的解決方案:
-
緩存擊穿: 通過 @Cacheable 注解的 sync 屬性,可以控制是否使用同步模式,以避免在高并發情況下多個線程同時查詢緩存失效的情況。
-
緩存穿透: 通過 @Cacheable 注解的 cache-null-values 屬性,可以緩存空值,防止對于一些不存在的 key,頻繁查詢底層數據源。
-
緩存雪崩: 通過設置緩存項的過期時間,以及使用隨機時間避免同時失效大量緩存項,可以減緩緩存雪崩問題的發生。
然而,寫模式中可能存在一些問題,比如緩存和底層數據源的一致性問題,因為在更新底層數據源和更新緩存之間存在一定的時間差。Spring Cache 沒有提供對寫模式問題的直接解決方案。在一些對數據一致性要求較高的場景中,可能需要結合其他手段(如數據庫事務、消息隊列等)來保證寫操作的一致性。