RabbitMQ-SpringBoot2

1.依赖引用


    org.springframework.boot
    spring-boot-starter-amqp

2.配置文件

spring:
  rabbitmq:
    host: 192.168.2.17
    port: 5672
    username: admin
    password: admin

3.配置类

这个类可以没有,但总提示,看着闹心

package com.example.rabbitmq.cluster;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ClusterConfig {

    public static final String queueName = "cluster.queue";
    public static final String exchangeName = "cluster.exchange";
    public static final String keyName = "cluster.key";

    @Bean("clusterQueue")
    public Queue queue() {
        Queue queue = QueueBuilder
                .durable(queueName)
                .build();
        return queue;
    }

    @Bean("clusterDirectExchange")
    public DirectExchange directExchange() {
        DirectExchange exchange = ExchangeBuilder
                .directExchange(exchangeName)
                .build();
        return exchange;
    }

    @Bean
    public Binding binding(@Qualifier("clusterQueue") Queue queue,
                           @Qualifier("clusterDirectExchange") DirectExchange directExchange) {
        return BindingBuilder.bind(queue).to(directExchange).with(keyName);
    }

}

4.消费者

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
 
@Slf4j
@Component
public class ClusterConsumer {

    @RabbitListener(queues = ClusterConfig.queueName)
    public void receiveMsg(Message message)
    {
        String msg = new String(message.getBody());
        log.info("[ClusterConsumer] 收到消息:{}", msg);
    }

}

5.生产者

package com.example.rabbitmq.cluster;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
 
@Slf4j
@RequestMapping("clu")
@RestController
public class ClusterController {

    private RabbitTemplate rabbitTemplate;

    public ClusterController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    @GetMapping("v1")
    public String v1() {
        rabbitTemplate.convertAndSend(ClusterConfig.exchangeName, ClusterConfig.keyName, "Cluster111");
        log.info("已经发送 Cluster111");
        return "已经发送 Cluster111";
    }

}

6.测试

你可能感兴趣的:(java,java-rabbitmq,rabbitmq,java)