[TIL 2024/09/11] HTTP Interface

2024. 9. 12. 01:59·TIL

프로젝트 수행 중 gemini API를 연동하면서 HTTP 인터페이스를 새로이 알게되었다.

옛날옛적에...약 4년전에 카카오나 네이버로 외부 api 연동할 때는 RestTemplate을 사용했었는데 ......

 

HTTP 인터페이스는 Spring6 에서 새롭게 추가 되었다고 한다.

 

HTTP Interface를 호출하면 요청될 구현체 생성

@Bean
public RestClient geminiRestClient(@Value("${gemini.api.url}") String baseUrl,
    @Value("${gemini.api.key}") String apiKey) {
    return RestClient.builder()
        .baseUrl(baseUrl)
        .defaultHeader("x-goog-api-key", apiKey)
        .defaultHeader("Content-Type", "application/json")
        .build();
}

@Bean
public AiInterface geminiInterface(@Qualifier("geminiRestClient") RestClient client) {
    RestClientAdapter adapter = RestClientAdapter.create(client);
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
    return factory.createClient(AiInterface.class);
}

(1) RestClient 객체를 생성하고 기본 URL 및 apiKey를 설정한다.

=>RestClient는 Http 요청을 보내는 역할

(2) RestClientAdaptor는 RestClient의 기능을 확장하는 역할

(3) RestClientAdaptor로 HttpServiceProxyFactory 생성 => Http 서비스의 프록시 객체를 생성한다.

(4) AiInterface는 HttpServiceProxyFactory 를 통해 프록시가 생성되고, 이 프록시 객체가 빈으로 등록된다.

(5) 프록시 객체는 AiInterface를 구현하는 클래스처럼 동작하며, 해당 인터페이스의 메서드를 호출하면 자동으로 HTTP 요청을 보내고 결과를 받아온다.

 

@HttpExchange("/v1beta/models")
public interface AiInterface {

    @PostExchange("{model}:generateContent")
    AiResponse getCompletion(
        @PathVariable String model,
        @RequestBody AiRequest request
    );
}

@HttpExchange : URL 경로를 지정한다.

@PostExchange : Post 요청 처리

 

요청 예시

public static final String GEMINI_PRO = "gemini-pro";

private final AiInterface aiInterface;

private AiResponse getCompletion(AiRequest request) {
    return aiInterface.getCompletion(GEMINI_PRO, request);
}

AiInterface의 getCompletion 호출 시 

https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent 로

AiRequest body를 들고

요청된다!

 

 

 

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

 

'TIL' 카테고리의 다른 글

[TIL 2024/09/30] 이미지 서버 모듈  (1) 2024.10.01
[TIL 2024/09/12] 공공 데이터 API service Key  (0) 2024.09.13
[TIL 2024/09/10] 프로그래머스 카드뭉치  (0) 2024.09.11
[TIL 2024/09/09] 스프링부트 AOP 사용해보기  (0) 2024.09.10
[TIL 2024/09/06] MSA 프로젝트 초기설정  (2) 2024.09.07
'TIL' 카테고리의 다른 글
  • [TIL 2024/09/30] 이미지 서버 모듈
  • [TIL 2024/09/12] 공공 데이터 API service Key
  • [TIL 2024/09/10] 프로그래머스 카드뭉치
  • [TIL 2024/09/09] 스프링부트 AOP 사용해보기
dev_ajrqkq
dev_ajrqkq
알고리즘 천재가 될 거야
  • dev_ajrqkq
    기록이 자산이다
    dev_ajrqkq
  • 전체
    오늘
    어제
    • 분류 전체보기 (158) N
      • Front-end (0)
      • Back-end (4)
        • Spring (1)
        • Java (8)
      • CS (9)
        • 데이터베이스 (5)
        • 네트워크 (4)
      • Algorithm (87) N
      • 이것저것 (0)
      • 버그잡기 (1)
      • TIL (37)
      • 후기 (3)
      • 취준 (0)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      코딩테스트준비
      99클럽
      환급챌린지
      습관형성
      오공완
      TypeScript
      패스트캠퍼스
      항해99
      직장인자기계발
      패스트캠퍼스후기
      오블완
      Til
      티스토리챌린지
      개발자취업
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.2
    dev_ajrqkq
    [TIL 2024/09/11] HTTP Interface
    상단으로

    티스토리툴바