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

相关推荐
代码中介商23 分钟前
LRU缓存算法:双向链表+哈希表实现
算法·链表·缓存
Micro麦可乐30 分钟前
最新Spring Security实战教程(十)权限表达式进阶 - 在SpEL在安全控制中的高阶魔法
java·spring boot·后端·spring·spring security·spel表达式
Wonderful U33 分钟前
基于Python+Django的文件预览与转换系统:从架构设计到完整实现
后端·python·django
忧郁的蛋~34 分钟前
ASP.NET Core Web API 完全指南:请求管道、认证、错误处理到生产部署
前端·后端·asp.net·.net
Jinkxs35 分钟前
Resilience4j- 非 Spring 环境集成:纯 Java 项目中的手动配置实现
java·后端·spring
可乐ea36 分钟前
【知识获取与分享社区项目 | 项目日记第 23 天】项目梳理下篇:高并发与最终一致性复盘:Redis、Kafka、Outbox、ES 与 RAG 如何协同
java·redis·mysql·elasticsearch·缓存·ai·kafka
拾光师41 分钟前
Python 列表(List)与元组(Tuple)详解
后端
右耳朵猫AI44 分钟前
Java/JVM周刊2026W21 | Java 26发布、JDK 27抢先体验、Spring Boot 4.1预告、GlassFish 8.0.2发布
java·jvm·spring boot
copyer_xyf1 小时前
Python 类全面总结
前端·后端·python
copyer_xyf1 小时前
Python 类型注解:从 TypeScript 迁移理解
前端·后端·python