MSA(7)-Kafkaを学ぶ


1.先行タスク

  • kafaインストール後メインキー、kafka
  • を実行
  • quickstart-イベントトピック
  • を作成

    2.ライブラリの追加

    implementation 'org.springframework.kafka:spring-kafka'

    3.KafkaProducerクラスの作成

    @Service
    @RequiredArgsConstructor
    public class Producer {
        private static final String TOPIC = "quickstart-events";
        private final KafkaTemplate<String,String> kafkaTemplate;
    
        public void sendMessage(String message){
            System.out.println("Send message = " + message);
            this.kafkaTemplate.send(TOPIC, message);
        }
    }

    4.KafkaConsumerクラスの作成

    @Service
    public class Consumer {
        @KafkaListener(topics = "quickstart-events", groupId = "con")
        public void consume(String message) throws IOException {
            System.out.println("rcv message = " + message);
        }
    }
    

    5.KafkaControllerの作成

    @RestController
    @RequestMapping(value = "/kafka")
    @RequiredArgsConstructor
    public class KafkaController {
        private final Producer producer;
    
        @PostMapping
        public String sendMessage(@RequestParam("message") String message){
            this.producer.sendMessage(message);
            return "success";
        }
    
    }
    

    6.KafkaControllerを呼び出す



    7.メールの送受信確認