OpenFeign
OpenFeign은 Netflix에서 처음 만든 Declarative HTTP Client 도구로 외부 API를
쉽게 호출할 수 있도록 돕는다고 하여 이번 프로젝트에서 BE-AI통신에서 사용하기로 하였다!
(Interface call 실패에 대한 대안인 fallback은 작성하지 않은 상태이니 참고바라요)
1. 의존성 추가하기
아래는 추가해야할 코드를 찾은 사이트이니 참고하기!
Maven Central: org.springframework.cloud:spring-cloud-starter-openfeign
Discover spring-cloud-starter-openfeign in the org.springframework.cloud namespace. Explore metadata, contributors, the Maven POM file, and more.
central.sonatype.com
기존에 있던 의존성에 추가로 OpenFeign과 관련된 의존성을 추가해준다.
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.3' //스프링부트 플러그인
id 'io.spring.dependency-management' version '1.1.0'//스프링 의존성
}
group = "com.lib"
version = "1.0-SNAPSHOT"
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:4.1.0'
implementation 'org.springframework:spring-web:6.1.8'
implementation 'io.github.openfeign:feign-core:13.2.1'
implementation 'io.github.openfeign:feign-slf4j:13.2.1'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer:4.1.3'
implementation 'org.springframework.cloud:spring-cloud-commons:4.1.3'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.test {
useJUnitPlatform()
}
2. OpenFeign 활성화
@EnableFeignClients → 메인 클래스에 붙여줌
package com.lib;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
@EnableFeignClients
@EnableJpaAuditing//자동으로 값이 들어감
public class SpringbootDeveloperApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDeveloperApplication.class,args);
}
}
3. 클라이언트에 대한 구성 클래스 생성
package com.lib.openFeign.feign;
import feign.Logger;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@EnableFeignClients
@Configuration
public class FeignClientConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
4. 클라이언트 인터페이스를 활용한 마이크로서비스 간 동기 통신
package com.lib.openFeign.feign;
import com.lib.openFeign.dto.AiRequest;
import com.lib.openFeign.dto.AiResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@FeignClient(name ="RecommendationFeignClient",url = "(맞춰서 넣어야 하는 부분)대상 URL:포트번호")
public interface RecommendationFeignClient {
@PostMapping(path = "/recommend")
AiResponse findAiRecommend(@RequestBody AiRequest reqDto);
}
5. 위 클라이언트 활용
Controller
@GetMapping("/recommend/main")
public ApiResponse<ApiResponse.CustomBody<List<MainAiRecommendResponse>>>findMainAiBook(HttpServletRequest request){
//Member memberId=(Member)request.getAttribute("memberId");
Long memberId = 1L;//기존
List<MainAiRecommendResponse> responseList=bookService.findByAiRecommendMain(memberId);
System.out.println("responseList(bookController 속 메인 ai요청):"+responseList);
return ApiResponseGenerator.success(responseList, HttpStatus.OK);
}
Service (여기에서 활용됨!)
public List<MainAiRecommendResponse> findByAiRecommendMain(Long memberId){
System.out.println("멤버 아이디:"+memberId);
List<String> isbnRequest =bookRepository.findByMemberId(memberId);
System.out.println("쿼리들어간 후:"+isbnRequest);
if (isbnRequest.isEmpty()) {
throw new IllegalArgumentException("not found" + memberId);
};
//프론트에서 백으로 요청-> 백은 해당 회원 아이디에 따른 관심 서재, 기록 테이블 속 책 id를 가져오고 (리스트)
// 그 리스트를 반복문에 넣어서 isbn 리스트를 생성-> ai에 넘김
AiRequest request = new AiRequest(isbnRequest); //ai에 보낼 isbn리스트 생성 완료
//--사용되는 부분 : findAiRecommend
AiResponse aiResponse= recommendationFeignClient.findAiRecommend(request);//응답
List<String> isbnList= aiResponse.getRecommended_isbns();
List<MainAiRecommendResponse> bookInfoList = new ArrayList<>();
for (String isbn : isbnList) {
Optional<Book> optionalBook = bookRepository.findByISBN(isbn);
if (optionalBook.isPresent()) {
Book eachBook = optionalBook.get();
MainAiRecommendResponse bookInfo = new MainAiRecommendResponse(eachBook);
bookInfoList.add(bookInfo);
}
}
return bookInfoList;
}
다음에는 좀더 체화시켜서 활용해봐야겠다는
생각과 이를 더 잘 활용해보고 싶다고 생각이 들었다.

*참고 블로그*
[Spring Cloud] Spring Cloud OpenFeign - 기본 개념 및 활용
Spring Cloud OpenFeign은 Spring Cloud 프로젝트에 포함된 동기 통신 클라이언트로, 선언적 REST 클라이언트로서 웹 서비스 클라이언트 작성을 보다 쉽게 할 수 있습니다.
velog.io
[Spring] OpenFeign이란? OpenFeign 소개 및 사용법
최근에 있었던 사내 엔지니어링 데이에서 발표를 하였는데, 상당히 편리하지만 많은 분들이 모르시는 OpenFeign을 준비하였습니다. 그리고 발표하면서 준비했던 내용을 블로그 포스팅에서도 적어
mangkyu.tistory.com
'프로젝트' 카테고리의 다른 글
[로그인 인가 인증] Refresh Token Rotation (0) | 2024.08.16 |
---|---|
[회고] 프로젝트 회고 <기록의 서재> (1) | 2024.08.11 |
[백엔드] 개발할 때 사용하면 좋은 프로그램 소개: JMeter (0) | 2024.08.05 |
[설계] AWS EC2내부 구조 설계 (아키텍쳐 설계 도구 링크 공유) (1) | 2024.06.09 |
[Database] 인덱스 파해치기 (0) | 2024.05.12 |