欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot集成Redis及SpringCache緩存管理示例詳解

 更新時間:2024年09月28日 15:14:01   作者:高高要努力  
本文介紹了如何在SpringBoot中集成Redis并使用SpringCache進(jìn)行緩存管理,詳解了Redis的配置、使用以及SpringCache的注解,還闡述了SpringCache的工作原理,包括其AOP實現(xiàn)和與各種緩存框架的集成,使得開發(fā)者可以輕松實現(xiàn)緩存功能,以提高應(yīng)用性能

1.集成Redis

1.導(dǎo)入依賴

<!--spirngboot springdata對redis支持-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置信息

#數(shù)據(jù)源配置
spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password: 123456
    jedis:
      pool:
        max-wait: 2000ms
        max-active: 8

3.注入redisTemplate使用

@RunWith(SpringRunner.class)  //使用springboot2.6.13的版本可以省略這個注解
@SpringBootTest(classes = App.class) //如果測試類和啟動不在同一個包下classes必須要寫
public class SpringbootDataRedisApplicationTests {
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    public void test() throws Exception{
        redisTemplate.opsForValue().set("name","zs");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }
}

4.自定義配置redis中key和value的序列化

@Configuration
public class RedisConfig {
    // 注入Redis連接工廠
    @Resource
    private RedisConnectionFactory factory;
    /**
     * @Description: 自定義RedisTemplate對象注入Bean容器中
     * @Author: Neuronet
     * @Date: 2023/10/22 18:49
     **/
    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        // 1.創(chuàng)建一個RedisTemplate對象
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        // 2.指定Redis連接工廠
        redisTemplate.setConnectionFactory(factory);
        // 3.創(chuàng)建一個JSON格式序列化對象,此處使用的是Redis自己的的序列化器
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        // 4.指定除開hash數(shù)據(jù)類型之外的數(shù)據(jù)key和value使用什么序列化器
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setValueSerializer(serializer);
        // 5.指定hash數(shù)據(jù)類型的key和value序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        return redisTemplate;
    }
} 

2.SpringCahe緩存管理

1. SpringCache概述

Spring 3.1 引入了激動人心的基于注解(annotation)的緩存(cache)技術(shù),它本質(zhì)上不是一個具體的緩存實現(xiàn)方案(比如EHCache 或者 OSCache),而是一個對緩存使用的抽象,通過在既有代碼中加入少量它定義的各種 annotation,即能夠達(dá)到緩存方法的返回對象的效果

Spring 的緩存技術(shù)還具備相當(dāng)?shù)撵`活性。不僅能夠使用 SpEL(Spring Expression Language)來定義緩存的 key 和各種 condition,還提供開箱即用的緩存暫時存儲方案,也支持和主流的專業(yè)緩存比如 EHCache 集成

說人話:SpringCahce對緩存流程進(jìn)行了簡化封裝,提供了一些注解,我們通過簡單的打注解就能實現(xiàn)緩存的添加,修改,刪除等,注解如下:

  • @Cacheable:觸發(fā)緩存寫入
  • @CacheEvict:觸發(fā)緩存清除
  • @CachePut:更新緩存(不會影響到方法的運(yùn)行)
  • @Caching:重新組合要應(yīng)用于方法的多個緩存操作
  • @CacheConfig:設(shè)置類級別上共享的一些常見緩存設(shè)置

2.SpringCache大致原理

1.Spring Cache利用了AOP,實現(xiàn)了基于注解的緩存功能,并且進(jìn)行了合理的抽象,業(yè)務(wù)代碼不用關(guān)心底層是使用了什么緩存框架,只需要簡單地加一個注解,就能實現(xiàn)緩存功能了,做到了對代碼侵入性做小。

2.由于市面上的緩存工具實在太多,SpringCache框架還提供了CacheManager接口,可以實現(xiàn)降低對各種緩存框架的耦合。它不是具體的緩存實現(xiàn),它只提供一整套的接口和代碼規(guī)范、配置、注解等,用于整合各種緩存方案,比如Caffeine、Guava Cache、Ehcache。

3.SpringCache注解

3.1. @Cacheable:寫緩存

方式一:@Cacheable可以用來進(jìn)行緩存的寫入,先也會根據(jù)緩存名和key去查詢,如果沒有查詢到,自動將方法的返回結(jié)果存儲在緩存中,以便于在后續(xù)調(diào)用的時候可以直接返回緩存中的值,而不必再執(zhí)行實際的方法

@Cacheable(cacheNames=“books”,key=”'book1'”)   // books::book1
public Book findBook(ISBN isbn) {.
  //查詢數(shù)據(jù)庫
  return 數(shù)據(jù);
}

方式二:一個方法可以對應(yīng)多個緩存名稱

@Cacheable(cacheNames={“books”, “isbns”},key=”'book1'”)
public Book findBook(ISBN isbn) {..…}

方式三@Cacheable的緩存名稱是可以配置動態(tài)參數(shù)的,比如選擇傳入的參數(shù),如下: (以下示例是使用SpEL聲明,如果您不熟悉SpEL,可以閱讀Spring Expression Language)

@Cacheable(cacheNames=“books”, key=“#isbn”) //參數(shù)值作為Key
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
@Cacheable(cacheNames=“books”, key=“#isbn.rawNumber”)
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

方式四

@Cacheable還可以設(shè)置根據(jù)條件判斷是否需要緩存

condition:取決于給定的參數(shù)是否滿足條件
unless:取決于返回值是否滿足條件(除非)

以下是一個簡單的例子:key有默認(rèn)的名字

@Cacheable(cacheNames=“book”, condition=“#name.length() < 32”) 
public Book findBook(String name)
@Cacheable(cacheNames=“book”,condition=“#name.length()<32”, unless=“#result.hardback”) 
public Book findBook(String name)

3.2. @CachePut:修改緩存

@CachePut:當(dāng)需要更新緩存而不干擾方法的運(yùn)行時 ,可以使用該注解。也就是說,始終執(zhí)行該方法,并將結(jié)果放入緩存(已經(jīng)有緩存就更新緩存),注解參數(shù)與@Cacheable相同。 以下是一個簡單的例子:

@CachePut(cacheNames="book", key="#isbn")
public Book updateBook(ISBN isbn, BookDescriptor descriptor) {
}

通常強(qiáng)烈建議不要對同一方法同時使用@CachePut和@Cacheable注解,因為它們具有不同的行為??赡軙a(chǎn)生不可思議的BUG哦

3.3. @CacheEvict:刪除緩存

@CacheEvict:刪除緩存的注解,這對刪除舊的數(shù)據(jù)和無用的數(shù)據(jù)是非常有用的。這里還多了一個參數(shù)(allEntries),設(shè)置allEntries=true時,可以對整個條目進(jìn)行批量刪除。 以下是個簡單的例子:

@CacheEvict(cacheNames="books", key="'book1'") 
public void loadBooks(InputStream batch)
//對cacheNames進(jìn)行批量刪除
@CacheEvict(cacheNames="books", allEntries=true) 
public void loadBooks(InputStream batch)

3.4. @Caching:組合注解

@Caching在使用緩存的時候,有可能會同時進(jìn)行更新和刪除,會出現(xiàn)同時使用多個注解的情況。而@Caching可以實現(xiàn)。 以下是個簡單的例子:

@Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames="secondary", key="#p0") })
public Book importBooks(String deposit, Date date)

3.5. @CacheConfig: 統(tǒng)一配置

@CacheConfig:緩存提供了許多的注解選項,但是有一些公用的操作,我們可以使用@CacheConfig在類上進(jìn)行全局設(shè)置。 以下是個簡單的例子:

@CacheConfig(cacheName="books") 
public class BookRepositoryImpl implements BookRepository {
    //注意:如果沒有指定key的話,keyGenerator會自動生成key導(dǎo)致刪除緩存失敗,所以下面的緩存操作需要指定key
    @Cacheable(key="'book1'")
    public Book findBook(ISBN isbn) {...}
}

4.SpringCache實戰(zhàn)

1.導(dǎo)入依賴

<!-- SpringCache依賴 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2.配置SpringCache集成redis

/**
 * @Description: SpringCache配置
 * @Author: Neuronet
 * @Date: 2023/10/22 19:32
 **/
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
    @Resource
    private RedisConnectionFactory factory;
    @Bean
    @Override
    public CacheResolver cacheResolver() {
        return new SimpleCacheResolver(cacheManager());
    }
    @Bean
    @Override
    public CacheErrorHandler errorHandler() {
        // 用于捕獲從Cache中進(jìn)行CRUD時的異常的回調(diào)處理器。
        return new SimpleCacheErrorHandler();
    }
    //緩存管理器
    @Bean
    @Override
    public CacheManager cacheManager() {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                        .disableCachingNullValues() //不允許空值
                        .serializeValuesWith(RedisSerializationContext.SerializationPair
                                             //值使用JSON序列化
                                             .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return RedisCacheManager.builder(factory).cacheDefaults(cacheConfiguration).build();
    }
}

3.開啟springCache

在啟動類注解:@EnableCaching

4.添加緩存

緩存注解不能加在內(nèi)部方法上,比如:方法A調(diào)用方法B,給方法B加上緩存注解會失效,因為內(nèi)部方法調(diào)用代理會失效,在A方法上打注解即可

//會先根據(jù)articleType::typeTree從redis獲取,如果有直接用緩存的。如果沒有就執(zhí)行方法體的代碼查詢數(shù)據(jù)庫
@Cacheable(cacheNames = "articleType", key = "'typeTree'")
public List<ArticleType> getTypeTree() {
    Object obj = redisTemplate.opsForValue().get("typeTree");
        if(obj == null){//redis沒有
            List<ArticleType> typeTree = typeTree();
            redisTemplate.opsForValue().set("typeTree",typeTree);
            return typeTree;
        }
    return typeTree();
}

到此這篇關(guān)于SpringBoot集成Redis及SpringCache緩存管理的文章就介紹到這了,更多相關(guān)SpringBoot集成Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論