Search
Duplicate
📒

노트 템플릿 시리즈

수업
Spring MSA
주제
기본개념
5 more properties
참고

MSA 개발

MSA 개발소개

NOTE
마이크로서비스 문제
동기식 통신을 사용하는 다수의 소형 컴포넌트는 연쇄장애 위험이 존재한다.
다수의 소형 컴포넌트를 최신 상태로 유지하기 힘듬
많은 컴포넌트 처리에 관한 요청은 추적하기 어려움
컴포넌트 수준의 하드웨어 자원 사용량 분석도 어려움
다수의 소형 컴포넌트를 수동으로 구성하고 관리할 때 비용이 많이 들고 오류가 발생하기 쉬움

마이크로 서비스 디자인패턴

NOTE
서킷브레이커 ⇒ 장애 확산을 방지하기 위한 방식
컨트롤 루프 ⇒ 리소스의 상태를 비교 관찰, GitOps 및 K8s에서 나오는 개념
WAS(Tomcat)없이 실행 가능하다. (내장톰캣 방식), JAR형태의 배포
실습환경 설정
# PowerShell 권한설정 Get-ExecutionPolicy Set-ExecutionPolicy AllSigned # Chocolatey 설치 (세션 정책변경, TLS 프로토콜 활성화) Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocol atey.org/install.ps1')) # 정상 실행 및 버전확인 choco choco install jdk11 choco install jq choco install spring-boot-cli
Shell
복사
Gradle관련 강의는 생략
PowerShell 실행 및 권한 모두허용
Chocolatey 설치
정살 실행 및 버전확인

Aspect 명시 (Component 스캔), Listener 설정

NOTE

Aspect

애플리케이션 클래스 자체를 설정 클래스로 만든다.
컴포넌트 검색을 활성화해 애플리케이션 모든 패키지에서 컴포넌트와 설정 클래스 검색
자동설정을 위해 Springboot가 설정 가능한 JAR파일을 classpath에서 자동으로 인식

Listener

@SpringBootApplication public class ProductServiceApplication { // .. // ContextRefreshedEvent => 새로고침시 발생 @EventListener(ContextRefreshedEvent.class) public void initIndicesAfterStartup() { // .. } }
Java
복사
Events란 Spring의 Bean - Bean 사이의 데이터 전달방법
Listener는 Publisher에서 발행된 이벤트를 사용하는 부분
@EnableBinding(Sink.class) // Spring Cloud Stream에서 사용하는 어노테이션 public class MessageProcessor { // .. // 이벤트 처리 @StreamListener(target = Sink.INPUT) public void process(Event<Integer, Product> event) { // ... } }
Java
복사
마이크로서비스의 Entity Topic에서 생성 및 삭제 이벤트를 수신하는 클래스 구현
하나의 Topic만 수식, Sink 인터페이스 바인딩을 위해 EnableBinding명시
수신 채널을 지정하고 메시지를 처리하는 메서드에 @StreamListener 명시
마이크로 서비스간 통신
@Bean RestTemplate restTemplate() { return new RestTemplate(); }
Java
복사
@Autowired public ProductCompositeIntegration( WebClient.Builder webClient, RestTemplate restTemplate, ObjectMapper mapper, @Value("${app.product-service.host}") String productServiceHost, @Value("${app.product-service.port}") int productServicePort ) { this.webClient = webClient.build(); this.restTemplate = restTemplate; this.mapper = mapper; productServiceUrl = "http://" + productServiceHost + ":" + productServicePort + "/product"; }
Java
복사
RestTemplate를 사용해서 HTTP 요청을 보낸다.
RestTemplate은 Spring Framework에서 제공하는 동기식 HTTP 클라이언트로, 웹 서비스와의 통신을 위해 사용됩니다. 주로 RESTful 서비스와의 통신을 위해 설계되었으며, 다음과 같은 기능을 제공합니다:
1.
HTTP 요청 전송: GET, POST, PUT, DELETE 등의 HTTP 메서드를 사용하여 웹 서비스에 요청을 보낼 수 있습니다.
2.
응답 처리: 서버로부터 받은 응답을 Java 객체로 변환합니다. 이를 위해 HttpMessageConverter 인터페이스를 사용하여 다양한 형식의 응답(예: JSON, XML)을 처리할 수 있습니다.
3.
오류 처리: HTTP 오류 발생 시 RestTemplate은 적절한 예외를 발생시킵니다. 이를 통해 오류 상황을 쉽게 처리할 수 있습니다.
4.
유연성: 요청 전송 전에 요청 헤더를 수정하거나, 인터셉터를 사용하여 요청/응답을 가로채는 등 다양한 사용자 정의 설정이 가능합니다.
RestTemplate은 동기 방식의 작동으로 인해 요청 처리 동안 현재 스레드가 차단(block)됩니다. 따라서, 높은 동시 요청 처리가 필요하거나 논블로킹 방식의 처리가 필요한 경우에는 WebClient와 같은 비동기 클라이언트를 사용하는 것이 좋습니다.
@Autowired HealthAggregator healthAggregator; @Autowired ProductCompositeIntegration integration; @Bean ReactiveHealthIndicator coreServices() { ReactiveHealthIndicatorRegistry registry = new DefaultReactiveHealthIndicatorRegistry(new LinkedHashMap<>()); registry.register("product", () -> integration.getProductHealth()); return new CompositeReactiveHealthIndicator(healthAggregator, registry); }
Java
복사
private Mono<Health> getHealth(String url) { url += "/actuator/health"; LOG.debug("Will call the Health API on URL: {}", url); return webClient.get().uri(url).retrieve().bodyToMono(String.class) .map(s -> new Health.Builder().up().build()) .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build())) .log(); }
Java
복사
Actuator 정보확인?

쿠버 API 설계

목차

NOTE

SpringFox

api: common: version: 1.0.0 title: Sample API description: Description of the API... termsOfServiceUrl: MINE TERMS OF SERVICE URL license: License licenseUrl: MY LICENSE URL contact: name: Contact url: My email: me@mail.com product-composite: get-composite-product: description: Returns a composite view of the specified product id notes: | # Normal response If the requested product id is found the method will return information regarding: 1. Base product information 1. Reviews 1. Recommendations 1. Service Addresses\n(technical information regarding the addresses of the microservices that created the response) # Expected partial and error responses In the following cases, only a partial response be created (used to simplify testing of error conditions) ## Product id 113 200 - Ok, but no recommendations will be returned ## Product id 213 200 - Ok, but no reviews will be returned ## Non numerical product id 400 - A <b>Bad Request</b> error will be returned ## Product id 13 404 - A <b>Not Found</b> error will be returned ## Negative product ids 422 - An <b>Unprocessable Entity</b> error will be returned
YAML
복사
@Api(description = "REST API for composite product information.") public interface ProductCompositeService { /** * Sample usage: curl $HOST:$PORT/product-composite/1 * * @param productId * @return the composite product info, if found, else null */ @ApiOperation( value = "${api.product-composite.get-composite-product.description}", notes = "${api.product-composite.get-composite-product.notes}") @ApiResponses(value = { @ApiResponse(code = 400, message = "Bad Request, invalid format of the request. See response message for more information."), @ApiResponse(code = 404, message = "Not found, the specified id does not exist."), @ApiResponse(code = 422, message = "Unprocessable entity, input parameters caused the processing to fails. See response message for more information.") }) @GetMapping( value = "/product-composite/{productId}", produces = "application/json") ProductAggregate getProduct(@PathVariable int productId); }
Java
복사
Spring으로 빌드된 API에 대한 자동화된 JSON API 문서 작성 프레임워크
Spirng Webflux, Swagger 어노테이션에서 얻은 정보를 바탕으로 문서제공
OpenAPI 지원

API 프로젝트 추가

RESTful API를 설명하는 부분 작성
Model Class로 API 요청 및 응답에 사용할 데이터 정의

AWS API Gateway

NOTE

제공하는 유형

RESTful API
HTTP API를 사용하여 서버리스 워크로드 및 HTTP 백엔드에 최적화된 API 구현
HTTP API는 프록시 기능만 필요한 API를 구축할때 가장 적합
WEBSOCKER
WebSocket API를 사용하여 채팅 앱 및 스트리밍 대시보드와 같은 실시간 양방향 통신 애플리케이션 구축
API Gateway는 백엔드 서비스와 클라이언트 간의 메세지 전송을 처리하기위해 연결유지

쿠버네티스 환경 구축

NOTE
# kubectl 다운로드 및 설치 확인 curl -o kubectl.exe https://s3.us-west-2.amazonaws.com/amazon-eks/1.22.6/2022-03-09/bin/windows/amd64/kubectl.exe kubectl version --short --client # eksctl 다운로드 및 설치 확인 choco install -y eksctl eksctl version aws eks로 kubeconfig 설정
Shell
복사

목차

NOTE

1. 목차

NOTE

목차

NOTE