Pink Spider/feign client 사용팁 - 상대 서버가 여러대 일때 랜덤 호출

Created Wed, 26 Mar 2025 08:37:45 +0900 Modified Mon, 08 Dec 2025 08:41:47 +0900
150 Words 1 min

feign client 사용팁 1 - 상대 서버가 여러대 일때 랜덤 호출

load balancing 되고 있는 상대측에 번갈아가면서 호출하는 방법

  • build.gradle
...
dependencies {
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}
...
  • application.yml
# 상대 측에서 3개의 서버 LB되고 있을 때 
other-party-url:
  - 123.456.789.001
  - 123.456.789.002
  - 123.456.789.003
  • ServerProperties.java
@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "other-party-url")
public class OtherServerProperties {

    private List<String> serverUris;
}
  • FeignConfig.java
@RequiredArgsConstructor
public class OtherServerFeignConfig {

    private final OtherServerProperties otherServerProperties;

    private final AtomicInteger counter = new AtomicInteger(0);

    @Bean
    public RequestInterceptor randomServerInterceptor() {
        return requestTemplate -> {
            List<String> serverUris = otherServerProperties.getServerUris();

            int index = counter.getAndIncrement() % serverUris.size();
            String selectedUrl = serverUris.get(index);

            requestTemplate.target(selectedUrl);
        };
    }
}
  • FeignClient interface
@FeignClient(name = "your-server", configuration = OtherServerFeignConfig.class)
public interface OtherServerFeignClientV1 {
    
    ...
}