使用Spring Cloud RabbitMQ 構建微服務架構

在現代的軟體開發中,微服務是一種流行的體系結構模式,它可以將大型應用程序拆分成小的單元,這些單元可以獨立的部署和擴展。在微服務架構中,每個服務都有自己的數據存儲,並通過 REST 或其他協議進行通信,這樣可以確保其他服務的故障不會影響整個系統的運作。使用Spring Cloud和RabbitMQ可以輕鬆構建微服務架構。

一、使用Spring Cloud與RabbitMQ創建基本的消息生產者和消費者

1、創建一個Spring Boot應用程序。在 pom.xml 文件中添加以下依賴:

   
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
   </dependency>
   

2、配置 RabbitMQ 的連接信息:

 
     spring.cloud.stream.rabbit.bindings.output.destination=myQueue
     spring.cloud.stream.rabbit.bindings.output.producer.routing-key-expression=payload
     spring.rabbitmq.host=localhost
     spring.rabbitmq.port=5672
     spring.rabbitmq.username=guest
     spring.rabbitmq.password=guest
  

3、定義一個生產者來發送消息:

 
    @EnableBinding(Source.class)
    public class OrderSender {
        @Autowired
        private MessageChannel output;
        public void send(String message) {
            output.send(MessageBuilder.withPayload(message).build());
        }
    }
  
 

4、定義一個消費者來接收消息:

 
    @EnableBinding(Sink.class)
    public class OrderReceiver {
        @StreamListener(Sink.INPUT)
        public void receive(String message) {
            System.out.println("Received message: " + message);
        }
    }
  

4、測試發送和接收消息:

 
    public static void main(String[] args) throws InterruptedException {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        OrderSender sender = context.getBean(OrderSender.class);
        for (int i = 1; i <= 10; i++) {
            sender.send("order-" + i);
            Thread.sleep(1000);
        }
        context.close();
    }
  

在控制台上可以看到消息的發送和接收的日誌。

二、使用Spring Cloud Config 為RabbitMQ添加外部配置信息

在微服務中,通常需要使用配置伺服器來集中管理配置信息。通過使用 Spring Cloud Config,可以輕鬆實現這一目標。

1、創建一個配置中心,用於存儲 RabbitMQ 配置信息。在 git 倉庫中,創建一個文件 amqp.properties,其中包含 RabbitMQ 連接信息。

 
    spring.rabbitmq.host=localhost
    spring.rabbitmq.port=5672
    spring.rabbitmq.username=guest
    spring.rabbitmq.password=guest
  

2、在配置中心的Spring Boot項目中添加以下maven依賴。

 
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-monitor</artifactId>
    </dependency>
  

3、將 RabbitMQ 配置信息添加到 bootstrap.yml 文件中:


    spring:
        cloud:
            config:
                server:
                    git:
                        uri: git@github.com:username/config-repo.git
                        search-paths: amqp
                        username: username
                        password: password
    rabbitmq:
        host: ${spring.rabbitmq.host}
        port: ${spring.rabbitmq.port}
        username: ${spring.rabbitmq.username}
        password: ${spring.rabbitmq.password}

4、在生產者和消費者應用程序中,在 消息通道綁定註解中添加參數來指定RabbitMQ 的交換機和隊列的名稱:


    @EnableBinding(value = {Source.class})
    public class Sender {
        @Autowired
        private Source source;
    
        public void sendMessage(String message) {
            source.output().send(MessageBuilder.withPayload(message).setHeader(MessageHeaders.CONTENT_TYPE,
                    MimeTypeUtils.APPLICATION_JSON).build());
        }
    }

使用與生產者類似的方式為消費者添加通道綁定注釋。

三、使用Spring Cloud Gateway將消息路由到微服務

在微服務架構中,通常需要使用 API 網關來聚合和路由消息。Spring Cloud Gateway是一個輕量級的 API 網關,可以根據路由規則將消息路由到不同的微服務中。

1、創建一個 Spring Boot 應用程序並添加以下 Maven 依賴:


    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>

2、創建一個配置文件 application.yml,並添加以下內容:


    spring:
        cloud:
            gateway:
                routes:
                    - id: order-service
                      uri: lb://order-service
                      predicates:
                        - Path=/api/orders/**
                    - id: payment-service
                      uri: lb://payment-service
                      predicates:
                        - Path=/api/payments/**
    server:
        port: 8080

3、使用該路由規則在網關中進行跨微服務消息調用,例如請求 http://localhost:8080/api/orders,該請求將被路由到 order-service 微服務中的 /api/orders URL。

四、使用Spring Cloud Stream實現事件驅動微服務

在微服務架構中,常用的一種模式是使用事件驅動架構來解耦微服務之間的依賴性。Spring Cloud Stream是一個簡單的事件驅動框架,它可以輕鬆整合 RabbitMQ 和 Apache Kafka。

1、創建一個 Spring Boot 應用程序,並添加以下 Maven 依賴:


    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
    </dependency>

2、創建一個簡單的事件發布者:


    public interface MessageSource {
        String OUTPUT = "orders-out";
        @Output(OUTPUT)
        MessageChannel messageOutput();
    }

3、創建一個簡單的事件消費者:


    public interface MessageSink {
        String INPUT = "orders-in";
        @Input(INPUT)
        SubscribableChannel messageInput();
    } 

4、打開 EventEmitter 的應用程序類並添加以下方法:


    @Autowired
    private MessageSource source;
    public void emitMessage(String message) {
        source.messageOutput().send(MessageBuilder.withPayload(message).build());
    }

5、打開 OrderReceiver 類並將 @EnableBinding 注釋移到類上,同時添加 @StreamListener:


    @StreamListener(OrderSink.INPUT)
    public void handle(String message) {
        System.out.println("Received message: " + message);
    }

6、在配置文件 application.yml 中添加以下配置:


    spring.rabbitmq.host: localhost
    spring.rabbitmq.port: 5672
    spring.rabbitmq.username: guest
    spring.rabbitmq.password: guest
    spring.cloud.stream.bindings.orders-out.destination: orders-exchange
    spring.cloud.stream.bindings.orders-in.destination: orders-exchange

7、運行 EventEmitter 和 OrderReceiver 應用程序。通過添加事件來測試應用程序。

結論

使用 Spring Cloud RabbitMQ,可以輕鬆構建消息驅動的微服務架構。Spring Cloud Config 可以使用外部配置管理 RabbitMQ 的連接信息,使用 Spring Cloud Gateway 路由消息,使用 Spring Cloud Stream 實現分散式事件處理來解除微服務之間的依賴關係。

原創文章,作者:NWNU,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/137965.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
NWNU的頭像NWNU
上一篇 2024-10-04 00:18
下一篇 2024-10-04 00:18

相關推薦

發表回復

登錄後才能評論