Spring Cache Redis配置

1.导入cache依赖包

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

2.yml配置 选择Redis作为存储

  cache:
    type: redis
    redis: #单位毫秒
      time-to-live: 360000
      key-prefix: CACHE_ #key前缀
      use-key-prefix: true #是否开启key前缀
      cache-null-values: true #是否缓存空值

3.编写RedisCacheConfig配置文件

package com.atguigu.gulimall.product.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 我RedisCache配置
 *
 * @author 万天铭
 * @date 2022/05/14
 */
@EnableConfigurationProperties(CacheProperties.class) //启用配置文件方式
@Configuration
@EnableCaching //开启RedisCache
public class MyCacheConfig {

    /**
     * RedisCache配置
     *
     * @return {@link RedisCacheConfiguration}
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        //将配置key value 序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));


       //将配置文件中的所有配置都生效
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
            if (redisProperties.getTimeToLive() != null) {
                config = config.entryTtl(redisProperties.getTimeToLive());
            }
            if (redisProperties.getKeyPrefix() != null) {
                config = config.prefixKeysWith(redisProperties.getKeyPrefix());
            }
            if (!redisProperties.isCacheNullValues()) {
                config = config.disableCachingNullValues();
            }
            if (!redisProperties.isUseKeyPrefix()) {
                config = config.disableKeyPrefix();
            }
        return config;
    }
}

(Cache在分布式下还是比较鸡肋的,个人推荐还是使用RedisTemplate比较好一点)

4.Spring Cache 注解作用

@Cachecble 触发将数据保存到缓存的操作

@CacheEvicet 触发将数据从缓存中删除 

@CachePut 不影响方法执行更新缓存

@Caching 组和以上的多个操作

@CacheConfig 在类级别共享缓存的相同配置

### 使用Spring CacheRedis集成 在构建微服务架构时,缓存对于提高应用程序性能至关重要。通过将`Spring Cache`与`Redis`集成,在分布式环境中可以实现高效的缓存管理。 #### 配置依赖项 为了使项目能够支持`Spring Cache`和`Redis`的功能,需添加如下Maven依赖到项目的`pom.xml`文件中: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-redis</artifactId> </dependency> ``` 这些依赖会自动配置必要的组件来启用基于注解的缓存功能以及连接至Redis服务器的能力[^4]。 #### 启用缓存机制 为了让应用识别并处理带有`@Cacheable`, `@CachePut`, 和 `@CacheEvict` 注解的方法调用,需要确保主类上已标注有`@EnableCaching`: ```java import org.springframework.cache.annotation.EnableCaching; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableCaching public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 此设置允许开发者利用声明式的编程方式轻松定义哪些方法的结果应该被存储于缓存之中。 #### 连接Redis实例 接下来要做的就是告诉Spring Boot怎样去访问外部的Redis数据库。这可以通过修改application.properties 或 application.yml 文件完成: ```properties # application.properties spring.redis.host=localhost spring.redis.port=6379 ``` 或者如果更倾向于YAML格式,则可以在`application.yml`里这样写: ```yaml # application.yml spring: redis: host: localhost port: 6379 ``` 上述配置指定了本地运行的一个默认端口上的Redis实例作为目标数据源[^2]。 #### 缓存具体业务逻辑 假设有一个简单的图书信息服务接口,其中包含了获取书籍详情的服务函数。现在希望通过引入缓存减少重复查询带来的开销: ```java @Service public class BookService { @Autowired private BookRepository bookRepository; /** * 获取指定ID编号对应的书目信息. */ @Cacheable(value="books", key="#id") public Optional<Book> findById(Long id){ System.out.println("Fetching from database..."); return this.bookRepository.findById(id); } // Other service methods... } ``` 这里的关键在于使用了`@Cacheable`注解标记了`findById()` 方法,这意味着每当请求相同参数(`id`)的数据时都会先尝试从名为“books”的缓存区域查找是否存在对应记录;只有当找不到匹配条目的情况下才会真正执行SQL语句并向客户端返回结果的同时也将其保存下来以便后续快速响应相同的请求[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值