如何在 Java Spring 应用程序中接受 GET/POST 请求之前预评估条件?

How to pre-evaluate condition before accepting GET/POST request in Java Spring Application?

我写了一个 class 来找出空闲内存的数量,使用 Runtime.getRuntime().freeMemory() class具有结构:

public class MemoryInfo 
{

private final long FREE_MEMORY = Runtime.getRuntime().freeMemory();

public long getFreeMemory() {
    return this.FREE_MEMORY;
 }

另一个 class 被写入接受 POST 请求,并且需要确保仅当此空闲内存高于某个阈值时才接受请求。如何确保这一点?该应用程序托管在 CloudFoundry 上。

编辑:另一个 class

 @Controller
public class StudentRegisterController {
    @RequestMapping(method = RequestMethod.POST, value = "/register/student")
    @ResponseBody
    StudentRegistrationReply registerStudent(@RequestBody StudentRegistration studentregd)  {
    StudentRegistrationReply stdregreply = new StudentRegistrationReply();
    MemoryInfo meminfo = new MemoryInfo();
    stdregreply.setName(studentregd.getName());
    stdregreply.setAge(studentregd.getAge());
    stdregreply.setRegistrationNumber("12345678");
    stdregreply.setRegistrationStatus("Successful");
    return stdregreply;
    }
}

您可以实现处理程序拦截器。

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

        return Runtime.getRuntime().freeMemory() > anumber;
    }

}

并在你的 WebMvcConfigurer 中定义它

@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer  {
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(new MyInterceptor()).addPathPatterns("/register/student");

     }
}