基于springboot简化版配置
1.maven配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.application.yml配置
spring:
rabbitmq:
host: localhost
port: 5672
username: admin
password: asdD#5123@
virtual-host: soa
rabbit:
queue: test888
exchange: test888
routingkey: test888
3.消费者端监听代码
package com.example.amqp_test.receiver;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class PaymentReceiver {
@RabbitListener(bindings = @QueueBinding(
value=@Queue(value = "${rabbit.queue}",durable = "true"),
exchange = @Exchange(value = "${rabbit.exchange}"),
key="${rabbit.routingkey}"))//动态申明,这里面不能在有queues ="" 注解了否则会报错
private void handleMessage(Message message) {
try {
if(Objects.isNull(message)){
return;
}
String ss =new String(message.getBody());
System.out.println("msg is {}"+ss);
// LogUtils.COMMON.info("subscribe :{}"+ new String(message.getBody()));
//todo
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.启动类
package com.example.amqp_test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AmqpTestApplication {
public static void main(String[] args) {
SpringApplication.run(AmqpTestApplication.class, args);
}
}
4.测试效果
可以看到自动申明成功了