RabbitMQ #1 demo
spring.rabbitmq.host=127.0.0.1 spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest
Config
package com.example.demo;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class RabbitMQCongig {
@Bean
public Queue testQueue() {
return new Queue("testQueue");
}
@Bean
public DirectExchange testExchange(){
return new DirectExchange("testExchange");
}
@Bean
public Binding bindTestQueue() {
return BindingBuilder.bind(testQueue()).to(testExchange()).with("testRoutingKey");
}
}
Sender
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
public RabbitTemplate rabbitTemplate;
Logger logger = LoggerFactory.getLogger(this.getClass());
public void send(String msg) {
logger.info("=========================== 发送消息开始" + " ===========================");
logger.info("发送消息:【 " + msg + " 】");
rabbitTemplate.convertAndSend("testExchange","testRoutingKey", msg);
logger.info("=========================== 发送消息结束" + " ===========================");
}
}
消费者
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "testQueue")
public class Receiver {
Logger logger = LoggerFactory.getLogger(this.getClass());
@RabbitHandler
public void process(String msg){
logger.info("=========================== 接收消息开始" + " ===========================");
logger.info("接收消息:【 " + msg + " 】");
logger.info("=========================== 接收消息结束" + " ===========================");
}
}
浙公网安备 33010602011771号