如何在Java Spring Application中接受GET / POST请求之前预先评估条件?

时间:2018-08-24 08:51:18

标签: java spring spring-boot cloudfoundry

我编写了一个类,使用 Runtime.getRuntime()。freeMemory()来查找可用内存量,该类具有以下结构:

public class MemoryInfo 
{

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

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

编写了另一个类来接受POST请求,并且需要确保仅在此可用内存超过某个阈值时才接受请求。如何保证呢?该应用程序托管在CloudFoundry上。

编辑:另一个类

 @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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

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");

     }
}