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 中。

相关推荐
前端兰博19 分钟前
分库分表
数据库
智能收银研究所1 小时前
收银系统选型对比:美团、客如云、拉卡拉、收钱吧各适合什么门店
java·前端·数据库
七夜zippoe2 小时前
金仓 Kingbase 安装与 Java 连接(保姆级):从装库到 JDBC 跑通全记录
java·数据库·jdbc·kingbase·金仓
stormsha3 小时前
中文路径让 MySQL 起不来:Failed to find valid data directory 与 Illegal byte sequence
运维·数据库·mysql
stormsha4 小时前
MySQL 报 `data directory has files in it`:初始化失败一次,之后就永久起不来
运维·数据库·mysql
goehou4 小时前
Redis 哨兵切换要多久,我量了一次
redis·故障转移·高可用·哨兵
YYYing.5 小时前
【Redis剑指offer系列 (一) 】Redis数据结构
数据库·redis·缓存·八股
csdn_aspnet5 小时前
使用 Docker 配置 PostgreSQL 和 pgAdmin 4
数据库·docker·postgresql·pgadmin4
真上帝的左手7 小时前
4. 关系型数据库-MySQL-原生集成 AI能力
数据库·人工智能·mysql·ai
琳少_7 小时前
java课堂笔记
java·开发语言·数据库·笔记