springboot整合RabbitMQ

 

一、加入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

二、在application.properties文件配置RabbitMQ

#IP地址
spring.rabbitmq.host=localhost
#rabbitmq默认端口号
spring.rabbitmq.port=5672
#账户名和密码
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
spring.rabbitmq.publisher-confirms=true

三、Topic 示例

1、单生产者-单消费者

加入queue

@Configuration
public class RabbitConfig {
    public static final String TOPIC_QUEUE1 = "topic.queue1";

    @Bean
    public Queue topicQueue1() {
        return new Queue(TOPIC_QUEUE1);
    }
}

编写生产者与消费者 

@Component
public class Topic1 {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String sendMsg = "helloWorld1 " + new Date();
        System.out.println("Sender1 : " + sendMsg);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_QUEUE1, sendMsg);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE1)
    public void process(String hello) {
        System.out.println("Receiver1  : " + hello);
    }

}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private Topic1 topic1;
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       //单生产者-单消费者
       topic1.send();
    }
}

启动springboot项目

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

2、单生产者-多消费者

加入queue

@Configuration
public class RabbitConfig {
    public static final String TOPIC_QUEUE2 = "topic.queue2";
    
    @Bean
    public Queue topicQueue2() {
        return new Queue(TOPIC_QUEUE2);
    }
}

编写生产者与消费者 

@Component
public class Topic2 {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send(String msg) {
        String sendMsg = msg + new Date();
        System.out.println("Sender1 : " + sendMsg);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_QUEUE2, sendMsg);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE2)
    public void process1(String hello) {
        System.out.println("消费者1 Receiver1  : " + hello);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE2)
    public void process2(String hello) {
        System.out.println("消费者2 Receiver2  : " + hello);
    }

}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private Topic2 topic2;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
        //单生产者-多消费者
        topic2.send("hello");
    }
}

启动springboot项目

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

3、多生产者-多消费者

加入queue

@Configuration
public class RabbitConfig {
    public static final String TOPIC_QUEUE3 = "topic.queue3";
    
    @Bean
    public Queue topicQueue3() {
        return new Queue(TOPIC_QUEUE3);
    }
}

编写生产者与消费者  

@Component
public class Topic3 {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send1(String msg) {
        String sendMsg = msg + new Date();
        System.out.println("生产者-Sender1 : " + sendMsg);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_QUEUE3, sendMsg);
    }

    public void send2(String msg) {
        String sendMsg = msg + new Date();
        System.out.println("生产者-Sender2 : " + sendMsg);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_QUEUE3, sendMsg);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE3)
    public void process1(String hello) {
        System.out.println("消费者-Receiver1  : " + hello);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE3)
    public void process2(String hello) {
        System.out.println("消费者-Receiver2  : " + hello);
    }
}

 测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private Topic3 topic3;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       //多生产者-多消费者
       topic3.send1("hello1");
       topic3.send2("hello2");
    }
}

启动springboot项目 

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

4、实体类传输

加入queue

@Configuration
public class RabbitConfig {
    public static final String TOPIC_QUEUE4 = "topic.queue4";
    
    @Bean
    public Queue topicQueue4() {
        return new Queue(TOPIC_QUEUE4);
    }
}

实体类(必须实现序列化接口)

public class User implements Serializable {
    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

 编写生产者与消费者  

@Component
public class UserSender {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        User user=new User();
        user.setId("1");
        user.setName("fullmark");
        System.out.println("user send : " + user.getName()+"---"+user.getId());
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_QUEUE4, user);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE4)
    public void process(User user) {
        System.out.println("user receive  : " + user.getName()+"---"+user.getId());
    }

}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private UserSender userSender;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       //实体类传输
       userSender.send();
    }
}

启动springboot项目  

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

四、topic ExChange示例

 加入queue

@Configuration
public class RabbitConfig {
    //topic
    public static final String TOPIC_QUEUE1 = "topic.queue1";
    public static final String TOPIC_QUEUE2 = "topic.queue2";
    //exchange
    public static final String TOPIC_EXCHANGE = "topic.exchange";
    
    @Bean
    public Queue topicQueue1() {
        return new Queue(TOPIC_QUEUE1);
    }

    @Bean
    public Queue topicQueue2() {
        return new Queue(TOPIC_QUEUE2);
    }    

    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }
    
    @Bean
    public Binding topicBinding1() {
        return         BindingBuilder.bind(topicQueue1()).to(topicExchange()).with("topic.queue1");
    }

    @Bean
    public Binding topicBinding2() {
        return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with("topic.#");
    }
}

 编写生产者与消费者  

@Component
public class ExChange1 {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String msg1 = "I am topic.mesaage msg1======";
        System.out.println("生产者-sender1 : " + msg1);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_EXCHANGE, RabbitConfig.TOPIC_QUEUE1, msg1);

        String msg2 = "I am topic.mesaages msg2########";
        System.out.println("生产者-sender2 : " + msg2);
        this.rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_EXCHANGE, RabbitConfig.TOPIC_QUEUE2, msg2);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE1)
    public void process1(String msg) {
        System.out.println("消费者-topicMessageReceiver1  : " +msg);
    }

    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE2)
    public void process2(String msg) {
        System.out.println("消费者-topicMessagesReceiver2  : " +msg);
    }
}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private ExChange1 exChange1;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       //exChange
       exChange1.send();
    }
}

启动springboot项目  

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

五、fanout示例

Fanout 就是我们熟悉的广播模式或者订阅模式,给Fanout交换机发送消息,绑定了这个交换机的所有队列都收到这个消息

 加入queue

@Configuration
public class RabbitConfig {
    //fanout
    public static final String FANOUT_QUEUE1 = "fanout.queue1";
    public static final String FANOUT_QUEUE2 = "fanout.queue2";
    public static final String FANOUT_EXCHANGE = "fanout.exchange";
    
    @Bean
    public Queue fanoutQueue1() {
        return new Queue(FANOUT_QUEUE1);
    }

    @Bean
    public Queue fanoutQueue2() {
        return new Queue(FANOUT_QUEUE2);
    }

    @Bean
    public FanoutExchange fanoutExchange() {
        return new FanoutExchange(FANOUT_EXCHANGE);
    }

    @Bean
    public Binding fanoutBinding1() {
        return BindingBuilder.bind(fanoutQueue1()).to(fanoutExchange());
    }

    @Bean
    public Binding fanoutBinding2() {
        return BindingBuilder.bind(fanoutQueue2()).to(fanoutExchange());
    }
}

编写生产者与消费者

@Component
public class Fanout1 {
    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String msgString="fanoutSender :hello i am fanout";
        System.out.println(msgString);
        this.rabbitTemplate.convertAndSend(RabbitConfig.FANOUT_EXCHANGE,"abcd.ee", msgString);
    }

    @RabbitListener(queues = RabbitConfig.FANOUT_QUEUE1)
    public void process(String msg) {
        System.out.println("FANOUT_QUEUE1-Receiver  : " + msg);
    }

    @RabbitListener(queues = RabbitConfig.FANOUT_QUEUE2)
    public void process2(String msg) {
        System.out.println("FANOUT_QUEUE2-Receiver : " + msg);
    }

}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private Fanout1 fanout1;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       //fanout
       fanout1.send();
    }
}

启动springboot项目  

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

六、direct示例

消息中的路由键(routing key)如果和 Binding 中的 binding key 一致, 交换器就将消息发到对应的队列中。路由键与队列名完全匹配

加入queue

@Configuration
public class RabbitConfig {
    //redirect模式
    public static final String DIRECT_QUEUE1 = "direct.queue1";
    public static final String DIRECT_EXCHANGE = "direct.exchange";
    
    @Bean
    public Queue directQueue1() {
        return new Queue(DIRECT_QUEUE1);
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(DIRECT_EXCHANGE);
    }

    @Bean
    public Binding directBinding1() {
        return BindingBuilder.bind(directQueue1()).to(directExchange()).with("direct.admin");
    }
}

 编写生产者与消费者

@Component
public class Direct1 {

    @Autowired
    private AmqpTemplate rabbitTemplate;
    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        rabbitTemplate.convertAndSend(RabbitConfig.DIRECT_EXCHANGE, "direct.admin", context);
    }

    @RabbitListener(queues = RabbitConfig.DIRECT_QUEUE1)
    public void process(String msg) {
        System.out.println("DIRECT_QUEUE1-Receiver  : " + msg);
    }

}

测试

@Component
@EnableScheduling
public class RabbitmqTest {

    @Autowired
    private Direct1 direct1;
    
    /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
        direct1.send();
    }
}

启动springboot项目 

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}

 

七、回调示例

 加入queue

@Configuration
public class RabbitConfig {
    //topic
    public static final String TOPIC_QUEUE1 = "topic.queue1";
    public static final String TOPIC_QUEUE2 = "topic.queue2";
    //exchange
    public static final String TOPIC_EXCHANGE = "topic.exchange";
    
    @Bean
    public Queue topicQueue1() {
        return new Queue(TOPIC_QUEUE1);
    }

    @Bean
    public Queue topicQueue2() {
        return new Queue(TOPIC_QUEUE2);
    }    

    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }
    
    @Bean
    public Binding topicBinding1() {
        return         BindingBuilder.bind(topicQueue1()).to(topicExchange()).with("topic.queue1");
    }

    @Bean
    public Binding topicBinding2() {
        return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with("topic.#");
    }
}

设置回调配置

/**
 * @author fanghuanbiao
 */
public class RabbitCallbackConfig {
    @Value("${spring.rabbitmq.host}")
    private String addresses;

    @Value("${spring.rabbitmq.port}")
    private String port;

    @Value("${spring.rabbitmq.username}")
    private String username;

    @Value("${spring.rabbitmq.password}")
    private String password;

    @Value("${spring.rabbitmq.virtual-host}")
    private String virtualHost;

    @Value("${spring.rabbitmq.publisher-confirms}")
    private boolean publisherConfirms;

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(addresses+":"+port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        /** 如果要进行消息回调,则这里必须要设置为true */
        connectionFactory.setPublisherConfirms(publisherConfirms);
        return connectionFactory;
    }

    @Bean
    /** 因为要设置回调类,所以应是prototype类型,如果是singleton类型,则回调类为最后一次设置 */
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplatenew() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }
}

编写生产与消费者

@Component
public class CallBackSender implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private RabbitTemplate rabbitTemplatenew;

    public void send() {
        rabbitTemplatenew.setConfirmCallback(this);
        String msg="callbackSender : i am callback sender";
        System.out.println(msg );
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        System.out.println("callbackSender UUID: " + correlationData.getId());
        this.rabbitTemplatenew.convertAndSend(RabbitConfig.TOPIC_EXCHANGE,  RabbitConfig.TOPIC_QUEUE2, msg, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        System.out.println("callbakck confirm: " + correlationData.getId());
    }
    
    @RabbitListener(queues = RabbitConfig.TOPIC_QUEUE2)
    public void process(String hello) {
        System.out.println("消费者 Receiver1  : " + hello);
    }
}

测试

@Component
@EnableScheduling
public class RabbitmqTest {
    @Autowired
    private CallBackSender callBackSender;
    
     /**
     * 一秒钟
     */
    @Scheduled(cron = "00/1 * * * * ?")
    public void send(){
       callBackSender.send();
    }
}

启动springboot项目  

@SpringBootApplication
public class RabbitApp {
    public static void main(String[] args) {
        SpringApplication.run(RabbitApp.class, args);
    }
}
Spring Boot框架可以很容易地与RabbitMQ进行集成。为了实现这个目标,你需要在项目的依赖项中添加两个关键的依赖项。首先,你需要添加spring-boot-starter-amqp依赖项,它提供了与RabbitMQ进行通信的必要类和方法。其次,你还需要添加spring-boot-starter-web依赖项,以便在项目中使用Web功能。 在你的项目中创建两个Spring Boot应用程序,一个是RabbitMQ的生产者,另一个是消费者。通过这两个应用程序,你可以实现消息的发送和接收。生产者应用程序负责将消息发送到RabbitMQ的消息队列,而消费者应用程序则负责从队列中接收并处理消息。这样,你就可以实现基于RabbitMQ的消息传递系统。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合RabbitMQ](https://blog.csdn.net/K_kzj_K/article/details/106642250)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Springboot 整合RabbitMq ,用心看完这一篇就够了](https://blog.csdn.net/qq_35387940/article/details/100514134)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [undefined](undefined)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值