JAVA/Spring

RestClient 사용

영공쁘이 2025. 4. 3. 17:45

RestClient

  •   동기식 HTTP 클라이언트 [ 자바 객체에서 요청 ]

RestClient를 사용하려면, 다음과 같은 방법을 취한다.

 

1. restClient를 정의하는 곳 세팅(생성 등)

 - RestClient 프록시를 설정

@Bean
  public ControlService controlService(ClientHttpRequestFactory requestFactory) {
    RestClient client = RestClient.builder()
                                  .requestFactory(requestFactory)
                                  .baseUrl("설정한 URL")
                                  .defaultStatusHandler(HttpStatusCode::isError, (request, response) -> {
                                    HttpStatusCode statusCode = response.getStatusCode();
                                    log.error("에러코드: {}", statusCode);
                                  }).build();

    RestClientAdapter adapter = RestClientAdapter.create(client);
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
    return factory.createClient(ControlService.class);
  }

 

2. restClient의 http 메서드 사용하는 곳 세팅 (service)

HTTP 메서드 사용으로 : GetExchange, PostExchange .. etc. 

 

ex) 스프링 공식 문서 참조.

 

※ 프로젝트

public interface ControlService {

  @PostExchange(url = "/health/ctrl", contentType = MediaType.APPLICATION_JSON_VALUE)
  ResponseEntity<String> putCtrlInfo(@RequestBody ServerStatusCtrlParam param);

}

 

 

 

 

Bean으로 등록된 AppConfig에서 restClient를 사용하고자 한다.

 

 

 

 

 

 

 

 

 

 

참고

https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-http-interface

 

REST Clients :: Spring Framework

WebClient is a non-blocking, reactive client to perform HTTP requests. It was introduced in 5.0 and offers an alternative to the RestTemplate, with support for synchronous, asynchronous, and streaming scenarios. WebClient supports the following: Non-blocki

docs.spring.io

https://m.blog.naver.com/aservmz/222325616285