Java 消息中间件的使用 RabbitMQ + Kafka 简单Demo

引入依赖:

    
        
            org.springframework.kafka
            spring-kafka
            2.2.5.RELEASE
        
        
            org.apache.kafka
            kafka_2.12
            2.2.0
        
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.amqp
            spring-rabbit
            2.1.5.RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

 

 

发送端:

@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");
    }

 

你可能感兴趣的:(java)