기본 콘텐츠로 건너뛰기

냉장고 가계부 프로젝트 29

Ribbon을 통해서 API서버와의 로드밸런싱은 잘 작동한다. 하지만, fridge-service 서버가 추가로 등록되면 application.yml 파일을 열고 listOfServers 프로퍼티에 추가로 등록된 서버의 주소를 입력하고 다시 빌드해야하는 단점이 있다. 아이피, 포트를 직접 환경설정파일에 할당하는것도 마찬가지다.

Eureka 서버를 구성하고, fridge-service, fridge-web 서비스가 Eureka Client가 되어 Eureka 서버에서 서버목록을 제공받을 수 있으면, 위의 문제점을 해결할 수 있다.

fridge-eureka 프로젝트를 생성한다. 의존성은 Cloud Discovery 의 Eureka Server를 체크하고 Finish를 클릭한다.

SpringBootApplication 파일명을 EurekaServiceApplication으로 변경하고, @EnableEurekaServer 애너테이션을 추가한다.
@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {

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

application.properties 파일을 yml로 변경하고 다음과 같이 설정을 편집한다.
spring:
  application:
    name: eureka-server
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
logging:
  level:
    com.netflix.eureka: off
    com.netflix.discovery: off

애플리케이션명은 eureka-server 이며, port 8761번을 사용한다.
Eureka 서버가 기동하면 디폴트값으로 레플리카 노드를 찾는데 이것은 운영환경일 경우 복제노드를 따로 준비하는 경우에 필요하므로 로그를 끄고(logging.level.com.netflix), Eureka 서버 자신도 client로 등록시키려는 것 또한 하지 않기 위해 eureka.client 설정을 한다.

이제 eureka-server 를 기동하고 localhost:8761을 접속해보면 다음과 같은 화면을 확인할 수 있다.

아직 등록된 인스턴스가 없다.

fridge 서버를 Eureka 서버가 관리하는 eureka client로 등록하기 위해 fridge 프로젝트의 pom.xml 에 eureka-client 의존성을 추가한다.
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

spring-cloud-starter-netflix-eureka-client 의존라이브러리를 추가하고, Application.class 파일에 @EnableDiscoveryClient 애너테이션을 추가한다.
@SpringBootApplication
@EnableJpaAuditing
@EnableDiscoveryClient
public class FridgeApplication {

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

이제 서버를 실행하면 Eureka Server를 찾고 발견하면 서비스를 등록한다.

Fridge-service 가 등록되었다. 위에 Emergency 에러문구는 인스턴스의 숫자가 변경되었다고 경고하는 문구이다. fridge-service 가 호출되면 사라진다.

fridge-web 프로젝트도 마찬가지로 Eureka Client로 등록한다.


이제 Eureka 클라이언트가 서버와 동적으로 등록되고 삭제된다. 또한, Eureka 서버에서 Eureka 클라이언트들에게 동적으로 등록되고 삭제된 서버목록을 제공하므로 애플리케이션명으로 서로간의 통신이 가능하다. Eureka 내부적으로 Ribbon 모듈을 활용하기 때문에 fridge-web 프로젝트에서 ribbon 의존성을 굳이 중복해서 가져갈 필요가 없다.

fridge-web 프로젝트의 pom.xml에서 ribbon 의존성을 삭제한다(eureka-client 의존성은 그대로 둔다).
application.yml 파일에서 fridge-service 프로퍼티전부를 삭제한다.
이제 다시 서버를 구동해서 UI서버를 호출해보면 ribbon을 썻을때와 동일한 로그가 보이며 정상 작동한다.

이전글: 냉장고 가계부 프로젝트 28
다음글: 냉장고 가계부 프로젝트 29

이 블로그의 인기 게시물

냉장고 가계부 프로젝트 14

fridge-web 프로젝트에서 api 서버와 통신할때 URL을 매번 중복해서 입력하는 부분을 제거하기 위해 RestTemplate 빈 등록메서드를 수정한다. @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.rootUri("http://localhost:8081").build(); } builder에 rootUri 메서드를 호출해서 api 서버 url을 미리 설정하고 build해서 RestTemplate 객체를 반환하면 RestTemplate을 사용하는 부분에서는 root 다음 경로만 넘겨주면 된다. WebFoodController 클래스의 restTemplate 사용부분을 전부 수정한다. @GetMapping public String foods(Model model) { ResponseEntity<Resources<FoodCommand>> response = restTemplate.exchange("/foods", HttpMethod.GET, null, new ParameterizedTypeReference<Resources<FoodCommand>>() {}, Collections.emptyMap()); .... 다른 메서드들도 동일하게 수정한다. Food 클래스에서도 이제 더이상 사용하지 않는 Cloneable과 hashCode, equals 메서드를 정리한다. Guava 의존라이브러리도 다른곳에서는 사용하지 않으므로 정리한다. 식품에 대한 최소한의 기능은 구현하였다. 이번에는 냉장고 라는 개념을 모델링한다. 식품들이 들어가고 나가는 곳은 냉장고이기 때문에 냉장고라는...

냉장고 가계부 프로젝트 27

스프링 Data 에서 제공하는 @CreatedDate, @LastModifedDate 애너테이션을 이용해서 작성일자, 수정일자를 도메인객체가 생성되고, 수정될 때 관리될 수 있도록 한다. Spring Data를 쓰기 전에는 DB컬럼에 Date 타입의 등록일 컬럼을 추가하고 DEFAULT 값으로 SYSDATE 를 줘서 DB에 Insert 되는 시간에 등록일자 컬럼이 채워지는 방식을 사용했었고, Update 쿼리가 실행될때 수정일자 컬럼에 SYSDATE를 직접 Update 해주는 방식을 자주 썼다. 그 뿐만아니라, 등록일자와 더불어 등록한 사용자(ex: registerUser)를 식별하는 식별키(ex: userId, username ...) 를 Insert 쿼리가 실행될때 등록해주고, 수정한 사용자(ex: modifedUser)를 Update 쿼리에 설정하는 방식은 차후에 있을지도 모를 일에 대비해서 늘 반복해서 작업했다. 스프링 Data 에서 제공하는 JPA Audit 기능은 이런 코드의 반복을 줄여준다. 사용자 같은 경우 객체로 넘기면 객체의 식별자가 담긴다. 등록시간은 날짜형 타입이다. public class Blog { @CreatedBy private User user; @CreatedDate private LocalDateTime creadtedDate; } Blog 클래스의 User 객체는 @CreatedBy 애너테이션으로 선언되서 등록한 사용자를 나타내는 컬럼에 값을 입력할것이다. createdDate 필드는 도메인객체가 영속성 저장소에 반영되는 시간을 나타낸다. Fridge, Food 클래스에 등록일, 수정일만 먼저 적용한다. 두 클래스에 createdDate, lastModifedDate 멤버변수를 선언한다. @Data @NoArgsConstructor @Entity @EntityListeners(AuditingEntityListener.class) public class Fridge { ...

냉장고 가계부 프로젝트 10

API 가 어느정도 준비되었으므로, UI를 만든다. 별도의 프로젝트로 구성해서 API를 호출하는 방식으로 구성한다. 프로젝트명은 fridge-web이라고 정한다. 냉장고 가계부 프로젝트 1 을 참고한다. 새 프로젝트에서는 Dependencies를 Web, Thymeleaf, DevTools 세개를 체크한다. 프로젝트가 준비되면, pom.xml 파일을 연다. <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <gro...