포스트

(멋쟁이사자처럼_백엔드스쿨플러스) Day33 레드판다 적용을 통한 MSA구현

레드판다 연결하기

기본 설정

docker-compose 파일 생성

application.yml 설정

  • 레드판다와 연결하기 위해 application.yml에 kafka 설정을 추가한다.

    1
    2
    3
    4
    5
    6
    7
    
      kafka:
        bootstrap-servers: localhost:19092
        producer:
          value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
        consumer:
          value-deserializer: org.apache.kafka.common.serialization.ByteArrayDeserializer
        auto-offset-reset: earliest # 컨슈머가 처음 시작할 때 초기 오프셋을 설정(수업에서는 적용 X)
    

KafkaListener 등록

  • KafkaListener를 등록하여 Kafka로부터 메시지를 수신한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    @Component
    @RequiredArgsConstructor
    @Transactional
    public class NotiEventListener {
      private final NotiService notiService;
        
      //스프링 리스너
      @EventListener
      @Async
      public void listenPost(PostCreatedEvent event){
        notiService.postCreated(event.getPost());
      }
        
      //카프카 리스너
      @KafkaListener(topics = "post-created-1", groupId = "2")
      public void consume2(String message){
        System.out.println("Consumed message: " + message);
      }
    }
    

    kafka 레드판다 연결 확인

    1. 레드판다 컨테이너에서 “post-created-1” 토픽을 확인한다. Image
    1. http://localhost:8070 확인 Image
    1. docker 컨테이너에서 메시지 발행 (스프링에서 메시지 출력) Image

레드판다를 통한 MSA 구현

kafkaTemplate을 이용한 메시지 발행

  • GIT 레포
  • 스프링 publish와 마찬가지로 kafkaTemplate을 이용하여 메시지를 발행한다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
    @Service
    @RequiredArgsConstructor
    public class PostService {
      //... 생략
      
      //스프링 발행자
      private final ApplicationEventPublisher eventPublisher;
      
      //카프카 발행자
      private final KafkaTemplate<Object, Object> kafkaTemplate;
      
      public RsData<Post> write(Author author, String title, String content) {
        //... 생략
      
        //스프링 발행
        eventPublisher.publishEvent(new PostCreatedEvent(this, post));
      
        //카프카 발행
        kafkaTemplate.send("post-created-1", post.getId() + "번 글이 생성되었습니다.");
      
        return RsData.of(post);
      }
      //... 생략
    }
    
  • 게시글 생성시 메시지를 받는다.

    Image

레드판다 적용(객체 전달)

  • GIT 레포
  • 객체전달은 다음과 같다.

    1. 객체를 전달할 클래스를 만든다.
    2. kafkaConfig에 Serializer를 등록한다.
    3. produce하는 측에서 전달
    4. consume에 전달 받은 객체를 받는다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    //PostDto.java
    @AllArgsConstructor
    @NoArgsConstructor
    @Data //직렬화를 위해 Getter가 필요하다.
    public class PostDto {
      private String title;
      private String content;
    }
      
    //KafkaConfig.java
    @Configuration
    public class KafkaConfig {
      @Bean
      public RecordMessageConverter converter() {
        return new JsonMessageConverter();
      }
    }
      
    //PostService.java
    kafkaTemplate.send("post-created-1", new PostDto(post.getTitle(), post.getContent()));
      
    //NotiEventListener.java
    @KafkaListener(topics = "post-created-1", groupId = "2")
    public void consume2(PostDto postDto){
      System.out.println("Consumed message: " + postDto.toString());
    }
    

    Image

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.