• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

port 를 일정 범위안에서 랜덤하게 하면 discoveryService 에서 port를 다르게 인지합니다.

21.05.12 17:44 작성 조회수 459

0

server:
port: ${random.int(10000,51000)} #0
spring:
application:
name: my-first-service

eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
instance:
instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}

위처럼 서버의 Port 를 일정 범위안에서 랜덤하게 하면 아래와 같은 현상이 발생됩니다.

io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /192.168.40.24:34968
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
|_ checkpoint ⇢ org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter [DefaultWebFilterChain]
|_ checkpoint ⇢ HTTP GET "/first-service/welcome" [ExceptionHandlingWebHandler]
Stack trace:
Caused by: java.net.ConnectException: Connection refused
at java.base/sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) ~[na:na]
at java.base/sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:779) ~[na:na]
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:330) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:334) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:707) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:655) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:581) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493) ~[netty-transport-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.63.Final.jar:4.1.63.Final]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

{
"timestamp": "2021-05-12T08:33:11.458+00:00",
"path": "/first-service/welcome",
"status": 500,
"error": "Internal Server Error",
"message": "",
"requestId": "fc5008c3-1"
}
확인해보니 실제 first-service 에 열린 port와 discoveryService 에서 인지하는 서버가 서로 달랐습니다.
그러면 ${random.int(10000,51000)} 사용하면 안되는건가요?
server:
port: 0
이렇게 바꾸면 잘 됩니다.
 

답변 1

답변을 작성해보세요.

7

안녕하세요, 이도원입니다. 

말씀하신 것처럼, application.yml 파일에서 random.int를 사용하여 random port를 사용할 때, Eureka Server에 잘못된 포트 정보로 등록될 수 있습니다. 아래 이미지에서 첫번째는 port:  ${random.int(10000,51000)}를 이용하여 기동했을 때 로그이고, 두번째는 port: 0으로 설정하고 기동했을 때의 로그입니다. 

1. port:  ${random.int(10000,51000)}

2. port: 0

2개의 로그를 확인해 보시면, 첫번째는 Eureka에 Register 하는 작업 도중에 Port를 업데이트 한 다음 등록을 완료하고, 두번째는 Port를 업데이트 한 다음 등록 작업을 시작하고 마무리하고 있습니다. 이러한 과정에서 random.int를 사용했을 때, 중간에 한번 더 업데이트 된 Port 정보가 Eureka에 등록되고(실제 Application에서는 Port가 변경되지 않음), Eureka 대시보드에서 잘못된 포트 정보를 가지고 표시하고 있습니다. 따라서 Random Port를 사용하실 때는 port: random.int 방식 보다는 port: 0으로  설정하시는게 좋을 것 같습니다. port: 0를 사용하셔야 하는 또하나의 이유로는, 중복 포트가 있을 경우, 해당 포트를 우회해서 다른 값을 설정하지만, port: random.int에서는 중복 값이 나오는 경우에는 애플리케이션을 그대로 기동하려고 하기 때문에, 포트 충돌로 인해 애플리케이션이 기동되지 않을수 있습니다. 

추가로, 특정 범위를 지정하여 Random Port를 사용하실 려면, 아래와 같은 방법으로 처리해 보실 수 있습니다.

@Component를 갖는 클래스를 추가하시고 실행해 보시면, 

@Component
public class CustomizationPort implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

@Override
public void customize(ConfigurableServletWebServerFactory server) {
Random random = new Random();
var port = random.ints(10000, 51000)
.findFirst()
.getAsInt();

server.setPort(port);
}
}

다음과 같은 로그를 확인해 보실 수 있습니다. 

위에서 설명 드렸던 바와 같이, 포트를 업데이트 한 다음, Eureka 서버에 등록을 마무리하고 있습니다. 위와 같은 작업 하셨을 경우에도 정상적으로 Load Balancing 작업이 되시는 것을 확인할 수 있습니다. 

감사합니다.