There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

Introducing dependencies:

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

Configuration:

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 for specific topic destination: Hello output: binder: kafka1 destination: helloCopy the code

Startup configuration:

@SpringBootApplication @EnableBinding(value = {Sink.class, Source.class}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}Copy the code

Receiving and sending:

@Component public class Inputer { @StreamListener(Sink.INPUT) public void receive(Message<? > message) {system.out.println (" message received: "+ message.getpayload ()); } } @Component public class Outputer { @Autowired private Source source; public void send() { source.output().send(new GenericMessage<>("hello kafka")); }}Copy the code

Testing:

@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(); }}}Copy the code

Of course, this has certain limitations, that is, input and output can only be configured for one topic. If you want to use more than one topic, you can have a look inside the Sink and Source interfaces and configure your own interfaces according to their practices. Input and output in the configuration file correspond to the value of @input and @output annotations in Sink and Source.