简体   繁体   English

如何模拟离线 Spring Boot 应用程序

[英]How to mock an offline Spring Boot application

I have a Controller with an endpoint.我有一个带有端点的控制器。 I would like to disable this endpoint at runtime so that it looks like the application is offline for the user.我想在运行时禁用此端点,以便应用程序看起来像用户脱机。

Currently doing this to disable the endpoint:目前这样做是为了禁用端点:

private static final Map<RequestMappingInfo, HandlerMethod> requestMappings = new HashMap<>();

this.context.getHandlerMethods().forEach((k, v) -> {
    if (k.getPatternsCondition().getPatterns().contains("/customer")) {
      requestMappings.put(k, v);
    }
});
requestMappings.forEach((k, v) -> this.context.unregisterMapping(k));

And this to enable:这是为了启用:

requestMappings.forEach((k, v) -> this.context.registerMapping(k, v.getBean(), v.getMethod()));
requestMappings.clear();

This works like a charm, the beans are unregistered and registered at runtime.这就像一个魅力,bean 在运行时被取消注册和注册。 However when the user calls my application they get a 404 instead of a Connection timed out, which is what I was looking for.然而,当用户调用我的应用程序时,他们得到 404 而不是连接超时,这正是我正在寻找的。

I do understand why I am getting a 404. Requests still enter the application but the path isn't found because the beans aren't registered so it return sa 404. How do I go about tackling an "actual offline" situation that doesn't return anything at all.我确实理解为什么我会收到 404。请求仍然进入应用程序,但找不到路径,因为 Bean 未注册,因此它返回 sa 404。我如何解决“实际离线”情况,但没有根本不返回任何东西。

I don't really understand what can be a use-case for such a scenario.我真的不明白这种场景的用例是什么。

There are some approaches I can think of though:不过,我可以想到一些方法:

  1. Just stop the application.只需停止应用程序。 As was already stated in comments - the client will try to connect and will eventually run into connection timeout.正如评论中已经指出的那样 - 客户端将尝试连接并最终会遇到连接超时。

  2. Restart the application context "programmatically" without restarting the whole JVM. “以编程方式”重新启动应用程序上下文,而无需重新启动整个 JVM。 There is a tutorial about doing this.有一个关于这样做的教程

The second approach can be appealing only in conjunction with a property spring.main.web-environment=false that you should supply during the application context restart.第二种方法只能与属性spring.main.web-environment=false结合使用,您应该在应用程序上下文重新启动期间提供该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM