spring cloud 搭建(kafka 入门(二))

前面一篇,将了如何配置kafak:https://blog.csdn.net/hanjun0612/article/details/107667389

这一篇在上面的基础,扩展成2个微服务。

 

其实很简单。

就是在原来的基础上,把StreamReceiver 和 TestStream 拷贝到Service1服务中。

spring cloud 搭建(kafka 入门(二))_第1张图片

 

 代码如下:

StreamReceiver

package com.test.service1.controller.kafka;

import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

/**
 * @author Tyler
 * @date 2020/7/28
 */

@Component
@EnableBinding(value = {TestStream.class})
public class StreamReceiver {

    @StreamListener(TestStream.INPUT)
    public void receive(String message) {
        System.out.println("StreamReceiver: "+message);
    }
}

 

TestStream

package com.test.service1.controller.kafka;

import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.SubscribableChannel;

/**
 * @author Tyler
 * @date 2020/7/28
 */

public interface TestStream {
    String INPUT = "test-in";
    String OUTPUT = "test-out";
    @Input(INPUT)
    SubscribableChannel testIn();
    @Output(OUTPUT)
    MessageChannel testOut();

}

 

POM文件:

PS:这里spring版本是2.3.2,用的是Hoxton.SR6

之前用的1.5.4,会报错:kafka Could not convert message


        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
         
    
    
    
        1.8
        Hoxton.SR6
    



        
            org.springframework.cloud
            spring-cloud-starter-stream-kafka
            2.0.1.RELEASE
        

 

application.yml

spring:
  application:
    name: service1
  cloud:
    stream:
      kafka:
        binder:
          brokers: localhost:9092
      bindings:
        test-in: #TestStream 中 INPUT
          destination: testkafka

效果:

Service1:

spring cloud 搭建(kafka 入门(二))_第2张图片

Kafka:

spring cloud 搭建(kafka 入门(二))_第3张图片

 

你可能感兴趣的:(spring,cloud,spring)