Spring Cloud 2-RabbitMQ 集成(八)


 

 

通過消息隊列MQ做為通信中心,這里采用RabbitMQ.安裝方參考: https://www.cnblogs.com/linyufeng/p/9883905.html
也可以采用windows環境(建議初學者采用)

  1. 下載Erlang
  2. 下載RabbitMQ

啟動服務並啟動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

 


 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM