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

相关推荐
Tony Bai12 分钟前
“我曾想付钱给 Google 去工作”—— Russ Cox 深度访谈:Go 的诞生、演进与未来
开发语言·后端·golang
Mr.Pascal37 分钟前
Redis:主动更新,读时更新,定时任务。三种的优劣势对比
数据库·redis·缓存
serendipity_hky2 小时前
【SpringCloud | 第2篇】OpenFeign远程调用
java·后端·spring·spring cloud·openfeign
嘟嘟MD2 小时前
程序员副业 | 2025年11月复盘
后端·创业
SadSunset2 小时前
(15)抽象工厂模式(了解)
java·笔记·后端·spring·抽象工厂模式
汝生淮南吾在北2 小时前
SpringBoot+Vue养老院管理系统
vue.js·spring boot·后端·毕业设计·毕设
李慕婉学姐2 小时前
【开题答辩过程】以《基于springboot的地铁综合服务管理系统的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·spring boot·后端
期待のcode3 小时前
Springboot配置属性绑定
java·spring boot·后端
海上彼尚3 小时前
Go之路 - 6.go的指针
开发语言·后端·golang
gugugu.3 小时前
Redis 字符串类型完全指南:从原理到实战应用
数据库·redis·缓存