打开浏览器并访问:http://localhost:15672/,并使用默认用户guest登录,密码也为guest
如果有其他账号也可
主项目:消息发送者
在pom.xml中引入如下依赖内容,其中spring-boot-starter-amqp用于支持RabbitMQ
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
在application.properties中配置关于RabbitMQ的连接和用户信息,您可以搜索安装内容,在管理页面中创建用户。
程序创建了一个访问127.0.0.1:5672中springcloud的连接
主项目配置文件:
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
注入AmqpTemplate接口的实例来实现消息的发送,AmqpTemplate接口定义了一套针对AMQP协议的基础操作。
我们产生一个字符串(电话号码+验证码),并发送到名为ChA的队列中。
import java.util.Date;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Sender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String context = "hello,我是好人 " + new Date();
System.out.println("Sender : " + context);
this.rabbitTemplate.convertAndSend("ChA ", context);
}
}
建立另一个工程:
发送短消息的微服务:(先建立一个springboot工程)消息消费者
通过@RabbitListener注解定义该类对ChA队列的监听,并用@RabbitHandler注解来指定对消息的处理方法。所以,该消费者实现了对ChA队列的消费,消费操作为输出消息的字符串内容。
创建RabbitMQ的配置类RabbitConfig,用来配置队列、交换器、路由等高级信息。这里先以最小化的配置来定义,以完成一个基本的生产和消费过程。
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues=RabbitMqConfig.QUEUE_NAME)
public class Receiver {
@RabbitHandler
public void process(String message) {
System.out.println("Receiver : " + message);
}
}
创建应用主类:
package com.dxz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RabbitmqHelloApplication {
public static void main(String[] args) {
SpringApplication.run(RabbitmqHelloApplication.class, args);
}
}
创建单元测试类,用来调用消息生产:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = RabbitmqHelloApplication.class)
public class RabbitmqHelloApplicationTests {
@Autowired
private Sender sender;
@Test
public void hello() throws Exception {
sender.send();
}
}
application.properties,消费端RabbitMQ配置:
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.username=guest
spring.rabbitmq.password= guest
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.publisher-confirms=true