如何等待 Redis 缓存缓存信息

我正在使用spring-data-redis,并试图有一个可以测试我的缓存逻辑的junit。测试用例偶尔会工作。我猜如果缓存逻辑在调用第二个方法调用之前完成,那么它就可以工作了,否则它就会失败。如果有些人遇到过类似的问题,我想了解他们是如何做到这一点的。截至目前,我正在使用thread.sleep(),但正在寻找替代方案。


  @Test

  public void getUserById() {

  User user = new User("name", "1234");

when(userRepository.findbyId("1234")).thenReturn(Optional.ofNullable(user));

  // first method call

  User user1 = userService.findbyId("1234");


  assertThat(user.getName()).isEqualTo(user1.getName());

  assertThat(user.getId).isEqualTo(user1.getId());


  // sleeping the thread so to provide caching aspect sufficient time 

  // to cache the information

  try {

    Thread.sleep(1000);

  } catch (InterruptedException e) {

    e.printStackTrace();

  }

  // second method call, expecting cache to work.

  userCache = userService.findbyId("1234");

  verify(userRepository, never()).findbyId("1234");

  assertThat(user.getName()).isEqualTo(userCache.getName());

  assertThat(user.getId).isEqualTo(userCache.getId());

}


慕森王
浏览 90回答 2
2回答

千万里不及你

等待时间较短的运行时问题在分布式系统中非常普遍。为了解决等待测试断言太久的需要,有一个名为Waitility的小工具。有了这个,你基本上可以通过在特定的时间间隔内多次查询断言来做更聪明的等待,直到达到给定的超时(...以及更多)。关于您的示例,请尝试以下操作:        Awaitility.await()                 .pollInterval(new Duration(1, TimeUnit.SECONDS))                 .atMost(new Duration(10, TimeUnit.SECONDS))                 .untilAsserted(() ->                      User user1 = userService.findbyId("1234");                     assertThat(user1.getName()).isEqualTo(user.getName());关于问题的另一部分,在集成测试中,您实际上可以对实例执行某种预热,或者如果您有容器化集成测试(例如Docker),则可以对其发出一些第一个请求,或者在开始测试之前等待某个条件。Redis

桃花长相依

实际问题不在于线程等待时间。要使 Redis 缓存正常工作,需要跨越一个单独的线程。对于我的服务测试,我通过一个单独的测试用例对其进行了测试。 @Test public void getUserById() {   User user = new User("name", "1234");   when(userRepository.findbyId("1234")).thenReturn(Optional.ofNullable(user));    // first method call   User user1 = userService.findbyId("1234");   assertThat(user.getName()).isEqualTo(user1.getName());   assertThat(user.getId).isEqualTo(user1.getId()); } //ensure this test case is executed after getUserById. I used  //@FixMethodOrder(MethodSorters.NAME_ASCENDING) @Test public void getUserById_cache() {   User user1 = userService.findbyId("1234");   Mockito.verify(userRepository, never()).findbyId("1234")   assertThat(user.getName()).isEqualTo(user1.getName());   assertThat(user.getId).isEqualTo(user1.getId()); }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java