[SpringCloud] 로드밸런서 구현

Hannana·2024년 12월 26일

gateway와 eureka server 연동해보자.

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

우선 실행하는 server들 pom.xml에서 client 의존성 체크

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true

gateway yml을 위와 같이 바꿔줌

server:
  port: 8081
spring:
  application:
    name: first-service

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka

각 서버들을 eureka와 연결

gateway를 eureka 기반으로 변경하기

  • 변경 전
      routes:
          - id: first-service
            uri: http://localhost:8081/ 
            predicates:
              - Path=/first-service/**
  • 변경 후
      routes:
          - id: first-service #when the service comes in,
            uri: lb://FIRST-SERVICE
            predicates:
              - Path=/first-service/**

포트 static하게 해놓으면 그것밖에 못씀. 그러니까
유레카의 네이밍한 것으로 포워딩시켜주자는 의미.
위 설정을 적용 후 게이트웨이 port에 요청 다시 보내보니

잘 동작한다.
이제 각 서비스가 gateway-> eureka(discovery)를 거쳐 포트 바인딩되도록 바뀌었다.


여러 서버 돌리기

1) 포트 지정해서 두 개 이상 돌려보기
mvn clear compile package
java -jar -Dserver.port={포트 지정} target/first-service-0.0.1-SNAPSHOT.jar

둘 중 하나로 감.

2) 랜덤 포트 지정해서 무한정 돌리기
mvn spring-boot:run
java -jar target/first-service-0.0.1-SNAPSHOT.jar

server:
  port: 0
eureka:
  client:
  instance:
    instance-id: ${spring.application.name}:${spring.application.instance_id}:${random.value}

어떤 포트로 돌아가는지 인스턴스명으로 확인하게 해주는 설정임.

@GetMapping("/check")
public String check(HttpServletRequest request)
{
  log.info("Server port={}", request.getServerPort());
  return String.format("Hi, There This is a message from First Service on PORT %s",
  env.getProperty("local.server.port"));
}


요청이 들어왔을 때
번갈아가면서 포트 변경되어 호출되는 걸 볼 수 있다.

간단한 로드밸런서 구현 완료.

profile
(구) https://hansjour.tistory.com/ 이사옴. 성장하는 하루를 쌓아가는 블로그

0개의 댓글