sprintboot @Cacheable测试代码
时间: 2024-06-06 16:04:08 浏览: 14
在Spring Boot中,`@Cacheable`是一个注解,用于声明方法的输出结果应该被缓存起来,以提高应用性能。当你在一个服务方法上使用这个注解,Spring会自动将该方法的返回值放入缓存中,如果后续请求相同的参数,Spring Boot会直接从缓存中获取,而不是再次执行计算。
以下是一个简单的示例代码,演示了如何在Spring Boot控制器方法中使用`@Cacheable`:
```java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class MyController {
@Cacheable(value = "myCache", key = "#id") // 定义缓存名称和缓存key生成策略
public String fetchData(@PathVariable Long id) {
// 这里是实际的数据获取逻辑,例如数据库查询或远程调用
// 假设我们只是返回id作为示例
return "Data for ID: " + id;
}
}
```
在这个例子中:
- `value`属性指定了缓存名称("myCache")。
- `key`属性定义了缓存键的生成规则,这里使用`#id`表示直接使用方法参数id作为缓存键。
要测试这样的代码,你可以创建一个单元测试,使用`MockMvc`或者`WebClient`来发送GET请求,并检查缓存是否被正确填充和检索。例如:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private YourService yourService; // 如果数据来自其他服务,这里需要mock那个服务
@Test
public void testCacheable() throws Exception {
// 第一次请求,数据应被计算并存储到缓存
mockMvc.perform(get("/myEndpoint/1"))
.andExpect(status().isOk())
.andExpect(content().string("Data for ID: 1"));
// 第二次请求,数据应从缓存中获取,而不是再次计算
mockMvc.perform(get("/myEndpoint/1"))
.andExpect(status().isOk())
.andExpect(content().string("Data for ID: 1"));
// 验证第一次请求调用了yourService,第二次没有
verify(yourService, times(1)).fetchData(1); // 如果是模拟服务,这里验证方法调用次数
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)