一、SpringBoot整合abbitmq
1.1、消息发送者
工程配置
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.0</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies>
spring:rabbitmq:host: 192.168.200.110port: 5672username: guestpassword: 123456virtual-host: /
@SpringBootApplication
public class PMQMain {public static void main(String[] args) {SpringApplication.run(PMQMain.class,args);}
}
测试代码:
@SpringBootTest
public class MQTest {public static final String EXCHANGE_DIRECT = "exchange.direct.order";public static final String ROUTING_KEY = "order";@Resourceprivate RabbitTemplate rabbitTemplate;@Testpublic void test1(){rabbitTemplate.convertAndSend(EXCHANGE_DIRECT,ROUTING_KEY,"你好,沸羊羊");}
}
1.2、消息的接收者
工程配置
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.0</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>
spring:rabbitmq:host: 192.168.200.110port: 5672username: guestpassword: 123456virtual-host: /
logging:level:com.cjc.mq.listener.MyMessageListener: info
@SpringBootApplication
public class MQMain {public static void main(String[] args) {SpringApplication.run(MQMain.class,args);}
}
测试代码:
@Component
@Slf4j
public class MyMessageListener {public static final String EXCHANGE_DIRECT = "exchange.direct.order";public static final String ROUTING_KEY = "order";public static final String QUEUE_NAME = "queue.order";//监听+创建交换机与队列关系
// @RabbitListener(bindings = @QueueBinding(
// value = @Queue(value = QUEUE_NAME,durable = "true"),
// exchange = @Exchange(value = EXCHANGE_DIRECT),
// key = {ROUTING_KEY}))//监听@RabbitListener(queues = {QUEUE_NAME})public void getMessage(String date, Message message, Channel channel){log.info("接收消息为:" + date);}
}