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", "john@example.com");
    }
}

在需要缓存的方法上添加@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缓存方法返回值的示例。当然,实际项目中可能需要更复杂的缓存策略和配置,如设置缓存过期时间、缓存更新等,可以根据具体需求进行配置和优化。

相关推荐
毕设源码-朱学姐几秒前
【开题答辩全过程】以 个人健康管理系统为例,包含答辩的问题和答案
java·spring boot
qq_12498707535 分钟前
基于微信小程序的线下点餐系统的设计与实现(源码+论文+部署+安装)
spring boot·微信小程序·小程序·毕业设计
IT_Octopus23 分钟前
Java GZip 压缩实践 +实践思考 +进一步压榨性能和存储方案思考:Protobuf+ GZip
java·spring boot
计算机毕设匠心工作室1 小时前
【python大数据毕设实战】全面皮肤病症状数据可视化分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql
毕设源码-郭学长1 小时前
【开题答辩全过程】以 高校教材大管家系统为例,包含答辩的问题和答案
java·spring boot
摆烂工程师1 小时前
2025年12月最新的 Google AI One Pro 1年会员教育认证通关指南
前端·后端·ai编程
qq_12498707531 小时前
基于SpringBoot+vue的小黄蜂外卖平台(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·后端·mysql·毕业设计
i02081 小时前
Java 17 + Spring Boot 3.2.5 使用 Redis 实现“生产者–消费者”任务队列
java·spring boot·redis
代码与野兽2 小时前
AI交易,怎么让LLM自己挑选数据源?
前端·javascript·后端
天天摸鱼的java工程师2 小时前
JDK 25 到底更新了什么?这篇全景式解读带你全面掌握
java·后端