spring-cloud - spring-cloud-stream + kafka的使用

161 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

引入依赖:

<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-stream-binder-kafka</artifactId>
</dependency>

配置:

spring:
  cloud:
    stream:
      binders:
        kafka1:
          type: kafka
          environment:
            spring:
              kafka:
                host: 127.0.0.1
                port: 9092
                publisher-confirms: true
      bindings:
        input:
          binder: kafka1
          # hello 为指定的topic
          destination: hello
        output:
          binder: kafka1
          destination: hello

启动配置:

@SpringBootApplication
@EnableBinding(value = {Sink.class, Source.class})
public class DemoApplication {

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

}

接收与发送:

@Component
public class Inputer {

    @StreamListener(Sink.INPUT)
    public void receive(Message<?> message) {
        System.out.println("接收到的消息:" + message.getPayload());
    }

}

@Component
public class Outputer {

    @Autowired
    private Source source;

    public void send() {
        source.output().send(new GenericMessage<>("hello kafka"));
    }
}

测试:

@SpringBootTest
public class Test1 {

    @Autowired
    private Inputer inputer;

    @Autowired
    private Outputer outputer;

    @Test
    public void output() {
        outputer.send();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

当然这个有一定的限制,就是input和output只能配置一个topic,如果要使用多个,可以进入Sink和Source接口的内部看一看,根据它们的做法配置自己的接口。其中配置文件中input和output对应的就是Sink和Source中@Input和@Output的注解的value值。

在这里插入图片描述