SpringCache和Redis结合基本使用

Spring Cache和Redis结合使用是一种强大的缓存方案,它允许您将应用程序中的数据缓存在Redis中,以提高性能和减轻数据库负载。下面是一个使用Spring Boot、Spring Cache和Redis结合的简单示例,以演示如何进行配置和使用。

首先,确保您的Spring Boot项目已添加了Spring Cache和Spring Data Redis的依赖。

xml 复制代码
<!-- Redis依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Spring Cache依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

在application.properties或application.yml中配置Redis连接信息:

properties 复制代码
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword

创建一个Spring Boot服务类,并在其中定义一个带有缓存注解的方法:

java 复制代码
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Cacheable(value = "products", key = "#id")
    public Product getProductById(Long id) {
        // 模拟从数据库中获取产品的操作
        System.out.println("Fetching product from the database for id: " + id);
        return new Product(id, "Product " + id, 100.0);
    }
}

创建一个简单的Product实体类:

java 复制代码
public class Product {

    private Long id;
    private String name;
    private double price;

    public Product(Long id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
    // getters and setters
}

创建一个REST控制器,用于访问产品数据:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/product/{id}")
    public Product getProduct(@PathVariable Long id) {
        // 调用带有缓存注解的方法
        return productService.getProductById(id);
    }
}

在上述示例中,我们使用@Cacheable注解来标记getProductById方法,它会缓存方法的结果,使用products作为缓存的名称,并以id作为缓存的键。如果相同的id再次被请求,方法将不会再次执行,而是从Redis缓存中返回结果。

确保您已启动了Redis服务器,并且您的Spring Boot应用程序正确配置了Redis连接信息。现在,当您访问/product/{id}端点时,会触发getProductById方法,结果将被缓存到Redis中,以便下一次访问相同的id时可以从缓存中获取数据,而不是再次执行数据库查询。

Spring Cache 默认情况下使用字符串作为缓存值的数据结构。

如果您想在Spring Boot中配置Spring Cache以将缓存数据存储在Redis中,并且需要使用不同于默认的字符串数据结构(String)来存储数据,您可以通过以下步骤进行配置。

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class CacheConfig {

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 使用Jackson2JsonRedisSerializer序列化对象
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);

        RedisSerializationContext.SerializationPair<Object> serializationPair =
                RedisSerializationContext.SerializationPair.fromSerializer(serializer);

        RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(serializationPair)
                .entryTtl(Duration.ofMinutes(10)); // 设置缓存过期时间

        return RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(cacheConfig)
                .build();
    }
}

products 在 Redis 缓存中以 JSON 字符串形式存在。在示例的 CacheConfig 配置中,我们使用了 Jackson2JsonRedisSerializer 作为序列化器来序列化和反序列化缓存值,将对象转换为 JSON 字符串并存储在 Redis 中。

相关推荐
焗猪扒饭6 小时前
redis stream用作消息队列极速入门
redis·后端·go
数据组小组8 小时前
免费数据库管理工具深度横评:NineData 社区版、Bytebase 社区版、Archery,2026 年开发者该选哪个?
数据库·测试·数据库管理工具·数据复制·迁移工具·ninedata社区版·naivicat平替
悟空聊架构15 小时前
基于KaiwuDB在游乐场“刷卡+投币”双模消费系统中的落地实践
数据库·后端·架构
IvorySQL15 小时前
PostgreSQL 技术日报 (3月4日)|硬核干货 + 内核暗流一网打尽
数据库·postgresql·开源
进击的丸子18 小时前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
NineData1 天前
NineData智能数据管理平台新功能发布|2026年1-2月
数据库·sql·数据分析
IvorySQL1 天前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
ma_king2 天前
入门 java 和 数据库
java·数据库·后端
jiayou642 天前
KingbaseES 实战:审计追踪配置与运维实践
数据库
NineData2 天前
NineData 迁移评估功能正式上线
数据库·dba