通過消息隊列MQ做為通信中心,這里采用RabbitMQ.安裝方參考: https://www.cnblogs.com/linyufeng/p/9883905.html
也可以采用windows環境(建議初學者采用)
啟動服務並啟動web訪問界面
- linux啟動
rabbitmq-plugins enable rabbitmq_management
- windows啟動
rabbitmq-plugins.bat enable rabbitmq_management
訪問 http://localhost:15672/ 並登陸, 默認用戶名和密碼都是guest
Hello World 代碼示例
pom.xml
<!-- rabbitmq 客戶端 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
application.yml
spring:
application:
name: rabbitmq-hello
# 以下都是默認配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
提供者
@Component
public class Sender {
@Autowired
private AmqpTemplate template;
public void send(){
String msg = "hello: "+new Date().toString();
System.out.println("Sender: " + msg);
this.template.convertAndSend("hello", msg);
}
}
消費者
@Component
public class Receiver {
@RabbitListener(queues = "hello")
public void process(String hello){
System.out.println("Reciver: "+ hello);
}
}
隊列配置
@Configuration
public class RabbitConfig {
@Bean
public Queue queue(){
return new Queue("hello");
}
}
單元測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitmqHelloApplicationTests {
@Autowired
private Sender sender;
@Test
public void contextLoads() throws InterruptedException {
for (int i = 0; i < 1000; i++) {
Thread.sleep((long) (Math.random()*3000));
sender.send();
}
}
}
運行單元測試, 控制台打印:
Sender: hello: Wed Dec 26 13:46:35 GMT+08:00 2018
Reciver: hello: Wed Dec 26 13:46:35 GMT+08:00 2018
Sender: hello: Wed Dec 26 13:46:37 GMT+08:00 2018
Reciver: hello: Wed Dec 26 13:46:37 GMT+08:00 2018
Sender: hello: Wed Dec 26 13:46:38 GMT+08:00 2018
Reciver: hello: Wed Dec 26 13:46:38 GMT+08:00 2018
