【问题标题】:How to force stop/kill Spring Redis embedded server programmatically如何以编程方式强制停止/杀死 Spring Redis 嵌入式服务器
【发布时间】:2020-08-04 19:34:15
【问题描述】:

我正在使用 Redis 嵌入式服务器进行集成测试,我注意到使用 RedisServer.stop() 方法并没有真正停止模拟服务器。知道如何在我的测试用例中强制杀死它吗?

依赖:

        <!-- Redis test mock server  -->
        <dependency>
            <groupId>it.ozimov</groupId>
            <artifactId>embedded-redis</artifactId>
            <version>0.7.2</version>
            <scope>test</scope>
        </dependency>

缓存集成测试:

@SpringBootTest
@ActiveProfiles("test")
@ExtendWith({SpringExtension.class, RestDocumentationExtension.class})
class CacheServiceImplTest {

    private RedisServer redisServer;

    @MockBean
    private StoreRepository repo;

    @Autowired
    public ObjectMapper objectMapper;

    @Autowired
    private CacheService cacheService;

    @PostConstruct
    public void postConstruct() {
//        if (redisServer.isActive()) {
////            redisServer.stop();
//            Runtime.getRuntime().addShutdownHook(new Thread() {
//                public void run() { redisServer.stop(); }
//            });
//        }
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() {
//        redisServer.stop();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> redisServer.stop()));
        redisServer.stop();
    }


    @Test
    void saveStoreToRedis() {
        List<Store> stores = new ArrayList<>();
        initializeStores(stores);
        when(repo.findAll()).thenReturn(stores);
        List<StoreResponse> actualStoresResponse = storeDao.findAll();
        Assert.assertNotNull(actualStoresResponse);
//        cacheService.invalidateCache();
    }

}

我遇到了错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxx.CacheServiceImplTest.ORIGINAL': Invocation of init method failed; nested exception is java.lang.RuntimeException: Can't start redis server. Check logs for details.

但是当我手动杀死它时,一切正常。

lsof -i:6370
COMMAND     PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
redis-ser 80714 XXX    4u  IPv4 0x5c18b66bd501f58d      0t0  TCP localhost:6370 (LISTEN)
  kill -9 80714

【问题讨论】:

    标签: java spring spring-boot redis


    【解决方案1】:

    我正在使用 kotlin,但您可以修改它,使其更适合您的测试,但我正在使用它,它似乎正在杀死我创建的 RedisServer

    @AfterEach
    fun killkillkill() {
        if (redisServer.isActive) {
            redisServer.stop()
        }
    }
    

    请注意,如果您在测试完成之前停止测试,这似乎不会被触发

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      相关资源
      最近更新 更多