Как предварительно оценить условие перед принятием запроса GET / POST в приложении Java Spring? - PullRequest
0 голосов
/ 24 августа 2018

Я написал класс для определения количества свободной памяти, используя 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 голосов
/ 24 августа 2018

Вы можете реализовать перехватчик обработчика.

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

     }
}
...