引入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.12</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
发送端:
@Component
public class SendDemo {
@Autowired
RabbitTemplate rabbitTemplate;
@Autowired
KafkaTemplate kafkaTemplate;
public void sendR(String msg){
rabbitTemplate.convertAndSend("exchange","key",msg);
}
public void sendK(String msg){
kafkaTemplate.send("test",msg);
}
}
接收端:
@Component
public class receiveRabbit {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue", durable = "true"),
exchange = @Exchange(
value = "exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC),
key = "key"))
public void listen(String msg) {
System.out.println("接收消息:" +msg);
}
}
@Component
public class receiveKafka {
@KafkaListener(topics = {"test"},groupId = "test-consumer-group")
public void receive(String id){
System.out.println("test : "+ id);
}
}
测试:
@Autowired
SendDemo sendDemo;
@Test
public void sendR() {
sendDemo.sendR("R");
}
@Test
public void sendK() {
sendDemo.sendK("K");
}