Microservice Architecture
애플리케이션을 기능별로 나누고 여러 서비스로 만듭니다.
서비스 간에 정보를 공유하고 통합 기능을 수행하는 기술입니다.
MSA는 클라우드 네이티브 환경의 핵심 기술 중 하나 입니다.
Spring Cloud는 마이크로 서비스의 개발, 배포, 운영에 필요한 아키텍처를 쉽게 구성할 수 있도록 지원하는 Spring Boot 기반의 프레임워크
클라우드 컴퓨팅 모델을 최대한 활용하는 애플리케이션을 개발, 구축 및 실행하기 위한 방법론입니다.
애플리케이션 아키텍처를 설계 시점부터 클라우드 환경에 맞게 설계하여 클라우드 환경에 대한 의존성을 제거하는 것이 그 목적입니다.
MemberService 응용 프로그램을 클라이언트 서비스로 등록하고 멤버 도메인 컨트롤러가 RESTful 요청을 처리하도록 합니다.
pom.xml
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client
</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
💡 MSA 환경에서는 동적으로 IP와 포트번호를
지정하므로 지속적으로 변경됩니다.
MSA 환경에서 서비스 정보를 등록하고 관리하도록 지원합니다.
@SpringBootApplication
@EnableDiscoveryClient
public class MemberServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MemberServiceApplication.class, args);
}
}
DiscoveryClient로 등록
@Data
@AllArgsConstructor
public class Member {
private Long id;
private String name;
private String password;
}
@RestController
public class MemberController {
@GetMapping("/api/member")
public Member getMember() {
return new Member(1L, "Gachon", "gcu");
}
}
server:
port: 8081
spring:
application:
name: memberservice
eureka:
instance:
preferIpAddress: true
lease-renewal-interval-in-seconds: 30
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
💡 서버 포트 번호를 8081로 설정합니다.
preferIpAddress: 서비스 간 통신 시 IP가 먼저 사용됩니다.
lease-renewal-interval-inseconds : 30초마다 하트비트 전송
registerWithEureka: 서비스가 Eureka에 등록되도록 지정
fetchRegistry: 클라이언트가 서버의 등록된 인스턴스 목록을 캐시 하지 않도록 지정합니다.
defaultZone: 동일한 영역에서 유레카 서버 클러스터링 구성
OrderService 응용 프로그램을 HTTP 클라이언트 서비스(FeignClient)로 등록하고 구성원 서비스를 Feign 클라이언트로 등록합니다. HTTP 요청 매핑을 수행합니다.
pom.xml
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client
</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
💡 openfeingn: 원래 Netflix에서 만든 선언적
HTTP 클라이언트 도구로 외부 API 호출을 쉽게 할 수
있도록 도와줍니다. MSA 통신제공
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
@EnableFeignClients
: Netflix에서 개발한 Http
클라이언트입니다. HTTP 요청을 쉽게 생성하고 보낼
수 있도록 도와주는 객체입니다.
@Data
public class Member {
private Long id;
private String name;
private String password;
}
@FeignClient("memberservice")
public interface MemberServiceFeignClient {
@GetMapping(value = "/api/member", consumes = "application/json")
Member getMember();
}
@FeignClient("members ervice")
: memberservice 이름의 페인트 클라이언트를 지정합니다.
인터페이스 정의
/api/member 경로가 포함된 GET 요청이 오면 getMember가 호출되어 Member 객체를 json 형식으로 반환합니다.
@RestController
public class OrderController {
@Autowired
private MemberServiceFeignClient memberServiceFeignClient;
@GetMapping("/api/order")
public String order() {
return memberServiceFeignClient.getMember().getName() + " requested an order.";
}
}
FeinClient 객체변수를 통해 멤버이름을 Order서비스에서 가져와서 출력합니다.
server:
port: 8082
spring:
application:
name: orderservice
eureka:
instance:
preferIpAddress: true
lease-renewal-interval-in-seconds: 30
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://127.0.0.1:8761/eureka/
마이크로 서비스를 등록하고 장애 감지를 위해 넷플릭스의 유레카 서버를 구축합니다.
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
EurekaServer를 검색 서버로 등록
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
server:
serverUrl:
defaultZone: http://127.0.0.1:8761/eureka/
서버 포트 번호를 8761로 설정합니다.
Eureka 서버의 기본 포트 번호입니다.
API Gateway를 통해 마이크로 서비스의 라우팅을 관리하고 인증 및 보안에 대한 기능을 제공할 수 있습니다.
구성은 크게 GATEWAY, EUREKA, FALLBACKSERVER, ADMIN, DB, CONFIG-SERVER 및 GIT로 구성됩니다.
SCG(Spring Cloud Gateway)를 통한 여러 마이크로 서비스의 라우팅을 지원합니다.
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
@SpringBootApplication
@EnableDiscoveryClient
public class GcuGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GcuGatewayApplication.class, args);
}
}
server:
port: 8000
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: apigateway-service
cloud:
gateway:
routes:
- id: memberservice
uri: http://localhost:8081/
predicates:
- Path=/api/member/**
- id: orderservice
uri: http://localhost:8082/
predicates:
- Path=/api/order/**
References: 가천 SW 아카데미