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

相关推荐
葛小白11 天前
C#数据类型:string简单使用
服务器·数据库·c#
污斑兔1 天前
MongoDB的$sample是啥?
数据库·mongodb
马丁的代码日记1 天前
MySQL InnoDB 行锁与死锁排查实战演示
数据库·mysql
拍客圈1 天前
数据主站+副站做的设置
数据库
计算机学长felix1 天前
基于SpringBoot的“面向校园的助力跑腿系统”的设计与实现(源码+数据库+文档+PPT)
数据库·spring boot·后端
拜见老天師1 天前
使用mybatis-plus,实现将排序时,字段值为NULL的数据排在最后
java·mybatis
金仓拾光集1 天前
__工艺数据管理的范式转变:金仓数据库替代MongoDB实操实践__
数据库·mongodb
xiaogg36781 天前
redis-cluster集群配置部署
数据库·redis·缓存
运维小文1 天前
MySQL高可用方案MIC&mysqlCluster+mysqlRouter
数据库·mysql·mic·mysql高可用·mysqlcluster·mysqlrouter
不剪发的Tony老师1 天前
Redis Commander:一款基于Web、免费开源的Redis管理工具
数据库·redis