티스토리 뷰

 

 

FeignClient 란?

FeignClient는 Spring Cloud에서 제공하는 HTTP 클라이언트로, 선언적으로 RESTful 웹 서비스를 호출할 수 있도록 함

 

연결하려는 서비스 구조

MSA Project 배송 서비스에서 일부이다.


- Auth : 사용자 계정 정보를 보관한다.

- Slack : 서비스내 배송 정보를 담당자 슬랙 DM 으로 전송한다.

- Ai : gemini Ai 와 연결하여 예상 배송 완료 시간과 날씨 정보를 받아온다.

OpenFeign 으로 응답받기

의존성 추가

연결이 필요한 모든 서비스 (Auth, Slack, Ai)에 OpenFeign 의존성을 추가한다.

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

 

 

 

Application 에 어노테이션 추가

동일하게 모든 서비스에 어노테이션을 추가한다.

@SpringBootApplication
@EnableFeignClients
public class SlackApplication {

  public static void main(String[] args) {
    SpringApplication.run(ReservationApplication.class, args);
  }

 

 

응답을 보낼 엔드포인트 생성 (Auth-Service, Ai-Service)

Slack - service 는 Auth-service 를 통하여 사용자 정보를 얻는다.

auth-service 는 외부로 전달하기 위한 별도의 엔드포인트를 생성해 준다.

기존 컨트롤러가 아닌 내부 서비스 간의 요청을 위한 ClientController 를 별도로 구성했다.

@RestController
@RequiredArgsConstructor
@Slf4j
public class ClientUserController {

    private final UserQueryService userQueryService;

    @GetMapping("/api/v1/internal/auth/{userUuid}")
    public ResponseEntity<CommonResponse<ClientUserResponse>> getUser(
        @PathVariable String userUuid) {
        log.info("[ClientUserController] Get User about : {}", userUuid);
        return ok(userQueryService.getClientUserResponse(userUuid));
    }
}

 

 

요청을 보내고 응답을 받을 인터페이스 구현 (Slack-Service)

위에 설정한 엔드포인트로 요청을 보내는 인터페이스를 구현한다.

동일한 방식으로 Ai-Service 에 프롬프트를 생성하고 응답을 받는 인터페이스를 구현했다.

 

  • AuthClient
@FeignClient(name = "auth-service")
public interface  AuthClient {

  @GetMapping("/api/v1/internal/auth/{userUuid}")
  ResponseEntity<CommonResponse<ClientUserResponse>> getUser(
      @PathVariable String userUuid);

}

 

  • AiClient
@FeignClient(name = "ai-service")
public interface AIClient {

  @PostMapping("/api/v1/ai/internal/createResponse")
  ResponseEntity<CommonResponse<String>> createResponse(
      @RequestHeader(HEADER_USER_ID) String userUuid,
      @RequestBody PromptRequest prompt
  );
}

 

 

 

요청을 보낼 서비스에서 인터페이스를 호출 (Slack-Service)

AiClient 인터페이스와 AuthClient 인터페이스를 생성하여 해당 엔드포인트에 동일하게 요청을 보낸다.

@Service
@Transactional
@RequiredArgsConstructor
@Slf4j
public class SlackCommandService {

  private final AIClient aiClient;
  private final AuthClient authClient;

  private final SlackMessagesRepository slackMessagesRepository;

 public void createMessage(CreateMessageRequest request, String userUuid){

    PromptRequest prompt = PromptRequest.of(request);
    String message = Objects.requireNonNull(
            aiClient.createResponse(userUuid, prompt).getBody()).getResponse();
    log.info("[SlackCommandService] [createMessage] message ::: {}", message);

    ClientUserResponse customer = Objects.requireNonNull(
            authClient.getUserFromAuthService(request.getCustomerId()).getBody()).getResponse();
    log.info("[SlackCommandService] [createMessage] customer ::: {}", customer.getUsername());
    
    ClientUserResponse deliveryPerson = Objects.requireNonNull(
            authClient.getUserFromAuthService(request.getDeliveryPersonId()).getBody()).getResponse();
    log.info("[SlackCommandService] [createMessage] customer ::: {}", deliveryPerson.getUsername());
    
    	}
    }

 

 

 

추가로 주의해야 했던 점

feignClient 를 활용하여 다른 서비스의 응답을 받아오는 것은 생각보다 어렵지 않다.

하지만 로그를 관리하지 않으면 문제를 찾지 못하고 블랙홀로 빠지는 경우가 발생했다.

게이트웨이에 디버깅 설정을 반드시 추가하고, feign 양 끝에 로그를 남기도록 하여 오류를 추적할 수 있도록 하였다.

 

- 게이트웨이 설정

logging:
  level:
    com.netflix.eureka: DEBUG
    org.springframework.cloud.gateway: DEBUG
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함