feign client 사용팁 1 - 상대 서버가 여러대 일때 랜덤 호출
load balancing 되고 있는 상대측에 번갈아가면서 호출하는 방법
...
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}
...
# 상대 측에서 3개의 서버 LB되고 있을 때
other-party-url:
- 123.456.789.001
- 123.456.789.002
- 123.456.789.003
@Setter
@Getter
@Configuration
@ConfigurationProperties(prefix = "other-party-url")
public class OtherServerProperties {
private List<String> serverUris;
}
@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(name = "your-server", configuration = OtherServerFeignConfig.class)
public interface OtherServerFeignClientV1 {
...
}