自学内容网 自学内容网

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

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

  1. 添加依赖:在pom.xml中添加Spring Boot Redis依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis:在application.properties中配置Redis连接信息
spring.redis.host=localhost
spring.redis.port=6379
  1. 启用缓存:在Spring Boot主类上添加@EnableCaching注解启用缓存功能
@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  1. 创建一个需要缓存的服务类
@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来测试缓存
@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缓存方法返回值的示例。当然,实际项目中可能需要更复杂的缓存策略和配置,如设置缓存过期时间、缓存更新等,可以根据具体需求进行配置和优化。


原文地址:https://blog.csdn.net/qq_35915504/article/details/140557913

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!