springboot怎么使用rides 缓存方法的返回值 完整例子

好的,下面是一个使用Spring Boot和Redis缓存方法返回值的完整示例:

  1. 添加依赖:在pom.xml中添加Spring Boot Redis依赖
xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis:在application.properties中配置Redis连接信息
properties 复制代码
spring.redis.host=localhost
spring.redis.port=6379
  1. 启用缓存:在Spring Boot主类上添加@EnableCaching注解启用缓存功能
java 复制代码
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 创建一个需要缓存的服务类
java 复制代码
@Service
public class UserService {
    
    @Cacheable(value = "users", key = "#id")
    public User getUserById(Long id) {
        // 模拟从数据库获取User对象
        return new User(id, "John", "[email protected]");
    }
}

在需要缓存的方法上添加@Cacheable注解,指定缓存的名称和key。这里的key是方法参数id,表示根据id缓存User对象。

  1. 创建一个Controller来测试缓存
java 复制代码
@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}
  1. 启动应用,访问接口测试缓存效果
    启动Spring Boot应用,然后多次访问 http://localhost:8080/users/1,可以看到第一次访问时会从数据库获取User对象,之后的访问会直接从Redis缓存中获取,不会再查询数据库。

这就是一个简单的Spring Boot整合Redis缓存方法返回值的示例。当然,实际项目中可能需要更复杂的缓存策略和配置,如设置缓存过期时间、缓存更新等,可以根据具体需求进行配置和优化。

相关推荐
XMYX-017 分钟前
Spring Boot + Prometheus 实现应用监控(基于 Actuator 和 Micrometer)
spring boot·后端·prometheus
@yanyu6662 小时前
springboot实现查询学生
java·spring boot·后端
酷爱码2 小时前
Spring Boot项目中JSON解析库的深度解析与应用实践
spring boot·后端·json
AI小智3 小时前
Google刀刃向内,开源“深度研究Agent”:Gemini 2.5 + LangGraph 打造搜索终结者!
后端
java干货3 小时前
虚拟线程与消息队列:Spring Boot 3.5 中异步架构的演进与选择
spring boot·后端·架构
一只叫煤球的猫3 小时前
MySQL 8.0 SQL优化黑科技,面试官都不一定知道!
后端·sql·mysql
不凡的凡4 小时前
鸿蒙图片缓存(一)
缓存
写bug写bug4 小时前
如何正确地对接口进行防御式编程
java·后端·代码规范
不超限5 小时前
Asp.net core 使用EntityFrame Work
后端·asp.net