Spring Cloud Stream



Spring Cloud 란 ?

  • 마이크로서비스 구축을 위해 필요한 모든 라이브러리의 집합

Building distributed systems doesn't need to be complex and error-prone. Spring Cloud offers a simple and accessible programming model to the most common distributed system patterns, helping developers build resilient, reliable, and coordinated applications. Spring Cloud is built on top of Spring Boot, making it easy for developers to get started and become productive quickly.

  • Spring Cloud는 가장 보편화된(범용적인) 분산시스템 패턴에 대해서 단순하고 접근 가능한 프로그래밍 모델을 제공

  • 개발자가 복원성(resilient), 신뢰성(reliable), 조정된 어플리케이션(coordinated applications)을 구축할 수 있도록 지원

  • Spring Cloud는 '스프링 부트' 기반위에서 구성됨으로써 개발자가 쉽고 빠르게 만들 수 있고, 빠르게 생산성을 높일 수 있음.

[출처: spring.io]

당장의 관심사

  • microservices

    • Reactor, SpringBoot, Spring Cloud

  • Message brokers (Spring Cloud Stream)

    • Reactor기반 Apache Kafka, RabbitMQ


Spring Cloud Stream 이란 ?

  • 마이크로서비스간, 외부시스템간 메세시 통신에 필요한 기술, 또는 메세지 기반 마이크로 서비스를 구현하기 위한 기술

A lightweight event-driven microservices framework to quickly build applications that can connect to external systems. Simple declarative model to send and receive messages using Apache Kafka or RabbitMQ between Spring Boot apps.

외부시스템과 연결가능한 어플리케이션을 빠르게 생성할 수 있는 경량의 이벤트 기반 마이크로서비스 프레임워크

쉽게 얘기하면 메세지 기반 어플리케이션을 구축하기 위해 Rabbit-MQ 나 Apache Kafka 와 같은 메세지 브로커와 쉽게 바인딩 할 수 있는 프레임워크


아래의 라이브러리만으로 어플리케이션 구성 가능

<dependencyManagement>
   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-stream-dependencies</artifactId>
           <version>Fishtown.M2</version>
           <type>pom</type>
           <scope>import</scope>
       </dependency>
   </dependencies>
</dependencyManagement>
<dependencies>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-stream</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-stream-rabbit</artifactId> <!-- or '*-stream-kafka' -->
   </dependency>
</dependencies><repositories>
   <repository>
       <id>spring-milestones</id>
       <name>Spring Milestones</name>
       <url>https://repo.spring.io/libs-milestone</url>
       <snapshots>
           <enabled>false</enabled>
       </snapshots>
   </repository>
</repositories>
pom.xml



주요 어노테이션

  • @EnableBinding 메세지 브로커와의 연결(Binding) 담당

  • @StreamListener 메세지브로커의 이벤트 수신 (Input 인터페이스를 통한)

  • @InboundChannelAdapter 메세지를 전송받는 채널에 메세지를 내보내기 위한 어댑터 (Outpu 인터페이스를 통한)

  • @ToSend


주요 인터페이스

  • Sink: Identifies the contract for the message consumer by providing the destination from which the message is consumed.

  • Source: Identifies the contract for the message producer by providing the destination to which the produced message is sent.

  • Processor: Encapsulates both the sink and the source contracts by exposing two destinations that allow consumption and production of messages.

[출처: spring.io]

위의 어노테이션 선언만으로 메세지 브로커를 통해 외부메세지를 받기 위한 어플레케이션 생성가능

@SpringBootApplication
@EnableBinding(Sink.class)
public class VoteRecordingSinkApplication {

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

 @StreamListener(Sink.INPUT)
 public void processVote(Vote vote) {
     votingService.recordVote(vote);
}
}

  • 스프링부트 기반으로 간편하고 직관적인 어노테이션으로 빠른 개발이 가능

  • 개발자는 메세지브로커의 커넥션, 설정등에 신경쓰지 않고 비즈니스 로직에 집중할 수 있음


왜 메세지 기반 (Messaga-Driven) 기술이 필요한가?

  • 느슨한 결합이 가능하므로 분산시스템, 마이크로서비스간 협업 관계에 있어 상호 의존성을 배제 할 수 있다.

  • 상대시스템의 성능, 서버 상태에 전혀 영향을 받지 않는다.

  • 서로 시스템 정보를 몰라도 메세지 브로커 시스템간 메세지 교환-상호간 정보 교환-이 가능하다.

  • API 방식의 경우, 목적지 시스템의 성능과 서버의 상태에 직접적인 영향을 받기 때문에 예외처리, FallBack처리가 필수

  • 상대 시스템은 서로 독립적으로 인스턴스를 증가 감소할 수 있다.

  • 상호 정보 교환을 하는 시스템들은 서로가 어디에 위치하는지 (Endpoint가 어디인지), 어떤 기술기반인지 관심을 가질 필요가 없다. 알지 못한다. 오로지 메세지 전송(Pub) 과 수신(Sub)에만 관심을 가지면 된다.


메세지 브로커 를 이해하기 위한 주요개념

  • 프로토콜... 다 그말이 그말인 듯한 프로토콜, 뭐가 다른지는 사실 나도...

    • AMQP (Advanced Message Queuing Protocol)

    • STOMP (Streaming Text Oriented Message Protocol)

    • MTQQ (Message Queuing Telemetry Transport)

    • TCP/IP -> 다들 잘 아는 그거...

  • Connection : 발생자와 소비자, Broker 사이의 물리적인 연결

  • Channel - 외부에서 메세지 브로커를 통해 메세지를 주고받을 수 있는 채널, 논리적인 연결고리 (발행시스템과 구독시스템은 채널을 통해 Queue에 접근 )

  • Exchange - 메세지의 라우팅 규칙(교환자), 실제 메세지를 담는 Queue와 바인딩 됨.

  • Queue - 메세지의 최종 목적지


대표적인 메세지브로커 (external message broker)



RabbitMQ & Apache Kafka의 비교

  • 메세지 브로커의 대표 솔루션, 레퍼런스가 가장 많음


  • Apache Kafka RabbiMQ
    메세지 저장방식파일시스템Memory
    통신 프로토콜TCP/IPAMQP
    기능타 솔루션대비 뛰어난 메세지 처리 성능다양한 기능, 익스체인지(라우팅) 지원
    부가기능최소1번의 메세지 전송 보장자체 클러스터링 지원


메세지 브로커의 선택기준

  • 내구성, 범용성

    • 메세지의 전송 보장, 재처리, 보관

  • 범용성 - 실 서비스에 적용된 많은 레퍼런스, 기술자료, 샘플소스

  • 가용성 - 클러스터링 여부(무중단), 안정적인 메세지 처리성능

  • 관리의 용이성

    • 시스템의 느슨한 결합에 따라오는 또 다른 관리포인트

    • 최소한의 관리비용


  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기