Springboot中使用Rabbitmq的代码

使用之前先确认已安装rabbitmq

首先,在pom.xml中添加依赖

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

在application.yml中添加配置代码

spring:
  rabbitmq:
    listener:
      simple:
        acknowledge-mode: manual
    username: guest
    password: guest
    host: localhost
    port: 5672
    virtual-host: /

添加配置类,加上@Configuration和@Bean注解后会自动生成一个队列

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMq队列配置
 */
@Configuration
public class RabbitConfig {
    public static final String COIN_QUEUE ="COIN" ;

    @Bean
    public Queue getCoinQueue(){
        return new Queue(COIN_QUEUE,true);
    }
}

在要使用的类中添加import


import org.springframework.amqp.rabbit.core.RabbitTemplate;

然后注入模板


    @Autowired
    private RabbitTemplate rabbitTemplate;

之后就可以加入队列了,第一个参数是队列名,第二个参数是内容,可以是任意类型,也可以是对象

this.rabbitTemplate.convertAndSend(RabbitConfig.COIN_QUEUE, "test");//加入队列

最后是消费者代码,


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
@Component
public class Consumer {

    /**
     * 处理COIN的队列请求
     */
    @RabbitListener(queues = {RabbitConfig.COIN_QUEUE})
    public void handleCoinQueue(CoinConsumerEntity consumerEntity, Message message, Channel channel) {
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
           //在这里可以对接收的数据进行处理,包括持久化等操作
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            try {
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
    }

猜你喜欢

转载自blog.csdn.net/rui15111/article/details/81221102