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

引入依赖:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值