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

相关推荐
用户675704988502几秒前
Redis 分布式锁的 5个坑,真的是又大又深!!
redis·后端
用户6757049885022 分钟前
Go 程序员进阶必读:这 24 个经典的 Golang 错误,连老手都会栽跟头!
后端·go
用户69371750013844 分钟前
AI 领域的 Harness,到底是什么意思?
android·前端·后端
二宝哥4 分钟前
springboot项目使用Gradle工具实现依赖版本控制
java·spring boot·后端·gradle·版本
ITender20 分钟前
Nacos 迁移引发 Full GC 问题深度分析
后端·面试
Gatlin20 分钟前
逆向学习:我为什么放着文档不看,直接读字节码
后端
我不是外星人20 分钟前
一键还原任意网站,这套 Playwright + 多 Agent 工程流太猛了
前端·后端·ai编程
geovindu25 分钟前
java: Singleton Pattern
java·开发语言·后端·单例模式·设计模式·创建型模式
Nturmoils28 分钟前
JOIN 不是拼上就完事,多表查询这几个坑先跑一遍
数据库·后端
IT_陈寒1 小时前
Vue的v-if和v-show,我竟然用错了这么久
前端·人工智能·后端