1、引入maven依赖:
org.springframework.boot spring-boot-starter-amqp org.springframework.boot spring-boot-starter-test2、在application.properties中设置RabbitMQ的配置信息:
spring.application.name=rabbitmq-hello
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
3、建立一个消息的生产者:
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitmqTemplate;
public void send(){
String content = "hello" + new Date();
System.out.println("Sender:" +content);
this.rabbitmqTemplate.convertAndSend("hello", content);
}
}
生产者Send会像Queue=hello发送一条消息;
4、建议一个消息的消费者:
@Component
@RabbitListener(queues = “hello”)
public class Receiver {
@RabbitHandler
public void process(String hello){
System.out.println("Receiver:" + hello);
}
}
@RabbitListener表示对队列hello进行监听,@RabbitHandler指定对消息的处理方法;
5、创建一个RabbitMQ的配置文件:
@Configuration
public class RabbitConfig {
@Bean
public Queue helloQueue(){
return new Queue("hello");
}
}
这个配置文件只要是建立一个消息队列hello;
6、创建应用主类和单元测试类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class HelloApplicationTests {
@Autowired
private Sender sender;
@Test
public void hello(){
sender.send();
}
}
Direct交换机和topic交换机的用法:
@Bean
public Queue queueMessage(){
return new Queue(“topic_message”);
}
@Bean
public Queue queueMessages(){
return new Queue(“topic_messages”);
}
@Bean
TopicExchange exchange(){
return new TopicExchange(“exchage”);
}
//Direct交换机的绑定
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange){
return BindingBuilder.bind(queueMessage).to(exchange).with(“topic.message”);
}
//Topic交换机的绑定
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange){
return BindingBuilder.bind(queueMessages).to(exchange).with(“topic.#”);
}
//消息生产者
public void send(){
String content = “hello” + new Date();
this.rabbitmqTemplate.convertAndSend(“exchage”,“topic.message”,“topic_message”);
this.rabbitmqTemplate.convertAndSend(“exchage”,“topic.messages”,“topic_messages”);
}
第一个参数是exchange,第二个参数是routingkey,第三个参数是发送的消息message
消息消费者:
@Component
@RabbitListener(queues = “topic_message”)
public class Receiver1 {
@RabbitHandler
public void process(String hello){
System.out.println("Receiver1:" + hello);
}
}
@Component
@RabbitListener(queues = “topic_messages”)
public class Receiver2 {
@RabbitHandler
public void process(String hello){
System.out.println("Receiver2:" + hello);
}
}
3.广播交换机的用法:
就是banding的时候少了routingkey的绑定:
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange){
return BindingBuilder.bind(queueMessage).to(exchange);
}
然后发送数据的时候和RoutingKey没有关系,所以关键字可填可不填;