在 Spring Boot 应用中使用 Spring Cache 和 Redis 实现数据查询的缓存功能

简介: 在 Spring Boot 应用中使用 Spring Cache 和 Redis 实现数据查询的缓存功能

在 Spring Boot 应用中使用 Spring Cache 和 Redis 实现数据查询的缓存功能是一种常见的优化方法,可以显著提高应用程序的性能和响应速度。下面我将详细介绍如何配置和使用这两个技术来实现数据查询的缓存。

 

### 1. 添加依赖

 

首先,确保在 `pom.xml`(如果是 Maven 项目)或 `build.gradle`(如果是 Gradle 项目)中添加必要的依赖:

 

#### Maven 依赖

 

```xml
    org.springframework.boot
    spring-boot-starter-cache
    org.springframework.boot
    spring-boot-starter-data-redis
```

#### Gradle 依赖

 

```gradle
implementation 'org.springframework.boot:spring-boot-starter-cache'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
```

### 2. 配置 Redis

 

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

 

```properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=  # 如果有密码,请填写
spring.redis.database=0  # Redis数据库索引,默认为0
```

### 3. 配置 Spring Cache

 

在 Spring Boot 主类(带有 `@SpringBootApplication` 注解的类)或配置类上,使用 `@EnableCaching` 开启缓存功能,并配置一个 `CacheManager` 来管理缓存:

 

```java
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.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
 
@Configuration
@EnableCaching
public class CacheConfig {
 
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
 
        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(cacheConfiguration)
                .build();
    }
}
```

### 4. 使用缓存

 

在 Service 层的方法上使用 `@Cacheable` 注解来实现缓存功能。例如:

 

```java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
 
@Service
public class MyDataService {
 
    @Cacheable(value = "myDataCache", key = "#id")
    public String getDataById(Long id) {
        // 模拟查询数据库或其他耗时操作
        // 实际项目中,这里应该是从数据库或其他服务获取数据的逻辑
        System.out.println("Fetching data from method for id: " + id);
        return "Data for id " + id;
    }
}
```

在这个例子中,`@Cacheable` 注解的 `value` 属性指定了缓存的名称(例如 `myDataCache`),`key` 属性指定了缓存的键,这里使用方法的参数 `id` 作为缓存的键。

 

### 5. 测试缓存效果

 

编写一个简单的 Controller 来测试缓存效果:

 

```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 MyDataController {
 
    @Autowired
    private MyDataService myDataService;
 
    @GetMapping("/data/{id}")
    public String getDataById(@PathVariable Long id) {
        return myDataService.getDataById(id);
    }
}
```

### 6. 测试缓存

 

启动我们的 Spring Boot 应用程序,并访问 `http://localhost:8080/data/{id}`,多次访问相同的 `id`,可以观察到第一次访问会执行方法体内的逻辑,而后续访问将直接从 Redis 缓存中获取数据,不会再次执行方法体内的逻辑。

 

通过以上步骤,我们就成功地集成了 Spring Cache 和 Redis,实现了数据查询的缓存功能。这种方式非常适合于需要频繁访问和不经常变化的数据,可以有效减少数据库或其他服务的访问压力,提升系统的性能和响应速度。

目录
相关文章
|
5月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
641 2
|
6月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
5594 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
772 0
|
7月前
|
缓存 监控 Linux
Linux系统清理缓存(buff/cache)的有效方法。
总结而言,在大多数情形下你不必担心Linux中buffer与cache占用过多内存在影响到其他程序运行;因为当程序请求更多内存在没有足够可用资源时,Linux会自行调整其占有量。只有当你明确知道当前环境与需求并希望立即回收这部分资源给即将运行重负载任务之前才考虑上述方法去主动干预。
2061 10
|
7月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1181 3
|
Java Maven 数据库
SpringBoot核心应用第二弹
Spring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件。简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架
SpringBoot核心应用第二弹
|
XML 存储 Java
SpringBoot核心应用第一弹
pring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件。简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架
SpringBoot核心应用第一弹
|
5月前
|
JavaScript 安全 Java
基于springboot的大学生兼职系统
本课题针对大学生兼职信息不对称、权益难保障等问题,研究基于Spring Boot、Vue、MySQL等技术的兼职系统,旨在构建安全、高效、功能完善的平台,提升大学生就业竞争力与兼职质量。