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

相关推荐
forestsea10 分钟前
全解:Redis RDB持久化和AOF持久化
数据库·redis·缓存
叫我DPT11 分钟前
分享一个python启动文件脚本(django示例)
数据库·python·django
小五Z40 分钟前
Redis--事务
redis·分布式·后端·缓存
XXYBMOOO1 小时前
基于 Qt 的 BMP 图像数据存取至 SQLite 数据库的实现
数据库·c++·qt
Sunlight_7771 小时前
第五章 SQLite数据库:1、SQLite 基础语法及使用案例
java·linux·服务器·jvm·数据库·tcp/ip·sqlite
JhonKI1 小时前
【从零实现高并发内存池】内存池整体框架设计 及 thread cache实现
java·redis·缓存
嘉嘉king1 小时前
Mysql联表查询
数据库
镜舟科技2 小时前
NoSQL 与 NewSQL 全面对比:如何选择适合你的数据库方案?
数据库·starrocks·nosql·newsql·技术架构·实时数据分析
TDengine (老段)2 小时前
TDengine 语言连接器(Node.js)
大数据·c语言·数据库·物联网·node.js·时序数据库·tdengine
洛神灬殇2 小时前
【Redis技术进阶之路】「原理分析系列开篇」分析客户端和服务端网络诵信交互实现(服务端执行命令请求的过程 - 时间事件处理部分)
redis·后端