/spring-boot-rabbitmq

Spring Boot集成RabbitMQ示例

Primary LanguageJavaApache License 2.0Apache-2.0

spring-boot-rabbitmq

spring-boot结合RabbitMQ入门示例

1. 在maven配置文件中加入spring-boot-starter-amqp依赖

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

2. RabbitmqApplication

@EnableRabbit
@SpringBootApplication
public class RabbitmqApplication {

    private static final Logger logger = LoggerFactory.getLogger(RabbitmqApplication.class);

    public static void main(String[] args) throws Exception {
        SpringApplication.run(RabbitmqApplication.class, args);
         logger.info("RabbitmqApplication is starting!~>>>>");
    }

}

3. 消息Producer

@Component
public class RabbitMQProducer {
    @Autowired
    private AmqpTemplate amqpTemplate;

    public void send(Object msg) {		
    if(msg instanceof String) {
  	amqpTemplate.convertAndSend("wxjfkg", "wxjf", (String) msg);
    } else {
  	Gson gson = new Gson();
  	String message = gson.toJson(msg);
  	amqpTemplate.convertAndSend("wxjfkg", "wxjf", message);
        }
    }
}

4. 消息Consumer

@Component
public class RabbitMQConsumer {

  @RabbitListener(bindings = { @QueueBinding(
    exchange = @Exchange(value = "wxjfkg", autoDelete = "false", durable = "true"), 
    value = @Queue(value = "wxjf-queue", durable = "true", autoDelete = "false"),
    key = "wxjf") 
  })
  public void process(String msg) {
    System.out.println("msg: " + msg);
  }
}