日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

SpringBoot Cache 整合 Redis 緩存框架

作者:次時(shí)代小羊 更新時(shí)間: 2023-07-18 編程語言

文章目錄

    • 引入依賴
    • 配置 Redis
    • 啟動(dòng)類注解
    • 注解開發(fā)
      • @Cacheable
      • @CachePut
      • @CacheEvict
    • 注解屬性
      • cacheNames/value
      • key
      • keyGenerator
      • condition
      • unless
      • cacheManager
      • sync
    • SpEL 表達(dá)式

SpringBoot 提供了 SpringBootCache 框架作為 SpringBoot 的緩存統(tǒng)一框架,使用 SpringBootCache ,我們可以使用注解的方式使用緩存,從而避免了寫一些重復(fù)代碼的問題。

引入依賴

首先我們需要引入相關(guān)的依賴,Cache 是緩存框架的核心依賴,不過該框架只提供了各種操作的接口集合,并沒有具體的實(shí)現(xiàn)。

而接口之外,SpringBoot 提供了各種具體的實(shí)現(xiàn),比如:RedisCache,EhCache,ConcurrentMapCache等等。

Redis 依賴是為了使用 Redis 作為緩存而引入的,如果不使用 Redis 作為緩存,也可以將 Redis 的依賴替換為其他實(shí)現(xiàn)。

Jackson 是作為序列化工具。

  • Maven
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.7.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.3</version>
</dependency>
  • Gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-cache:2.7.3'
    implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.7.3'
    implementation 'org.springframework.boot:spring-boot-starter-test:2.7.3'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.3'
}

配置 Redis

因?yàn)槲覀円肓?SpringBootRedis 的依賴,Spring 會(huì)默認(rèn)使用 Redis 作為我們的緩存,所以需要配置 Redis 的信息。

  • application.yaml
spring:
  redis:
    host: 127.0.0.1
    port: 6379
  • RedisCacheManager
@Configuration
public class RedisCacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 使用緩存的默認(rèn)配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 使用 GenericJackson2JsonRedisSerializer 作為序列化器
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        new GenericJackson2JsonRedisSerializer()));
        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config);
        return builder.build();
    }
}

啟動(dòng)類注解

使用 SpringBootCache 作為緩存框架,我們需要在 SpringBoot 的啟動(dòng)類上添加 @EnableCaching 注解,這樣才能夠啟用緩存框架。

@EnableCaching
@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

注解開發(fā)

我們只需要在方法上面添加相關(guān)的注解,即可使用緩存邏輯,從而提升服務(wù)性能。

@Cacheable

該注解可以注解在方法和類上,當(dāng)被注解的類下的方法或者被注解的方法被調(diào)用時(shí),會(huì)先去緩存中查看是否有緩存數(shù)據(jù),有緩存數(shù)據(jù)則直接返回緩存數(shù)據(jù),無緩存數(shù)據(jù)則調(diào)用該方法,獲取該方法的返回值,并將該返回值存入緩存中。

@CachePut

該注解可以注解在方法和類上,當(dāng)被注解的類下的方法或者被注解的方法被調(diào)用時(shí),不管緩存中是否有對(duì)應(yīng)的緩存數(shù)據(jù),都會(huì)將該方法的返回值更新(插入或覆蓋)到緩存中。

@CacheEvict

該注解可以注解在方法和類上,當(dāng)被注解的類下的方法或者被注解的方法被調(diào)用時(shí),會(huì)直接刪除緩存中的緩存數(shù)據(jù)。

注解屬性

@Cacheable,@CachePut,@CacheEvict三個(gè)注解都有一些屬性。

cacheNames/value

用來指定緩存組件的名字。

@Cacheable(cacheNames = "user")
public User selectById(Integer id) {
	return new User(id);
}

key

緩存數(shù)據(jù)時(shí)使用的 key,可以用它來指定。默認(rèn)是使用方法參數(shù)的值。(這個(gè) key 你必須使用 spEL 表達(dá)式來編寫)

@Cacheable(cacheNames = "user", key = "#id")
public User selectById(Integer id) {
    return new User(id);
}

使用以上的配置,如果入?yún)⒌?id 值為 1Redis 會(huì)存入一個(gè) key 為 user::1 數(shù)據(jù)。

@Cacheable(cacheNames = "user", key = "#root.methodName")
public User selectById(Integer id) {
    return new User(id);
}

使用以上的配置,如果入?yún)⒌?id 值為 1Redis 會(huì)存入一個(gè) key 為 user::selectById 數(shù)據(jù)。

keyGenerator

key 的生成器。 key 和 keyGenerator 二選一使用。

@Bean
public KeyGenerator keyGenerator() {
    return (target, method, params) -> Arrays.asList(params).toString();
}

使用以上的配置,如果入?yún)⒌?id 值為 1Redis 會(huì)存入一個(gè) key 為 user::[1] 數(shù)據(jù)。

condition

可以用來指定符合條件的情況下才緩存。

@Cacheable(cacheNames = "user", key = "#id", condition = "#id > 1")
public User selectById(Integer id) {
    return new User(id);
}

unless

否定緩存。當(dāng) unless 指定的條件為 true ,方法的返回值就不會(huì)被緩存。當(dāng)然你也可以獲取到結(jié)果進(jìn)行判斷。(通過 #result 獲取方法結(jié)果)

該屬性相當(dāng)于 !condition 屬性。

@Cacheable(cacheNames = "user", key = "#id", unless = "#id > 1")
public User selectById(Integer id) {
    return new User(id);
}

cacheManager

可以用來指定緩存管理器。從哪個(gè)緩存管理器里面獲取緩存。

sync

是否使用異步模式。

SpEL 表達(dá)式

名字 位置 描述 示例
methodName root object 當(dāng)前被調(diào)用的方法名 #root.methodName
method root object 當(dāng)前被調(diào)用的方法 #root.method.name
target root object 當(dāng)前被調(diào)用的目標(biāo)對(duì)象 #root.target
targetClass root object 當(dāng)前被調(diào)用的目標(biāo)對(duì)象類 #root.targetClass
args root object 當(dāng)前被調(diào)用的方法的參數(shù)列表 #root.args[0]
caches root object 當(dāng)前方法調(diào)用使用的緩存列表(如 @Cacheable(value=[“cache1”,"cache2J),則有兩個(gè) cache) #root.caches[0].name
argument name evaluation context 方法參數(shù)的名字,可以直接使用 #參數(shù)名,也可以使用 #p0 或 #a0 的形式,0代表參數(shù)的索引。 #a0
result evaluation context 方法執(zhí)行后的返回值 (僅當(dāng)方法執(zhí)行后的判斷有效) #result

原文鏈接:https://blog.csdn.net/qq_45193304/article/details/131727266

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新