简体   繁体   中英

Design Pattern for handling Microservices requests

I have an application which is based on Microservices. I have a Broker/Gateway API which receives HTTP requests. Then I have two more services Service A and Service B. When the Broker API receives a message it uses RabbitMQ to send it to the services. Then in each one of them I should handle it and process it differently depending on the message (execute different action).

This is the way I handle the messages currently:

Service A

    public string ProcessAsync(Message message)
    {

        switch (message.EventCode)
        {
            case "context 1":
                return action1();
            case "context 2":
                return action2();
            case "context 3":
                return action3();
            case "context 4":
                return action4();
            case "context 5":
                return action5();
            default:
                throw new Exception("Unknown message event code!");
        }
    }

It makes sense to use switch statement if I have no more than 5 - 10 different message types. But in my app I have 30. Writing such a big conditional statement is ugly and different to maintain. I am looking for a design pattern that is going to remove this problem from the application. Do you have any ideas? What do you think about State Pattern?

You could try the CQRS architecture.

In CQRS every command has exactly one handler; as components you need to have a CommandDispatcher that uses a CommandSubscriber to dispatch every command to the right handler. After each command is executed, one or more events are generated; every event is also dispatched to one or more event handlers.

If every message has the same class, Message , then your CommandSubscriber should register command handlers based on the message.EventCode . If every message has a different class (ie Message is an interface ), then CommandSubscriber should register command handlers based on the message class. This architecture style respects the Open-close principle whereas your switch-based style does not.

It is "Gateway Routing Pattern" When it receives a request, the API gateway consults a routing map that specifies which service to route the request to. A routing map might, for example, map an HTTP method and path to the HTTP URL of service. This function is identical to the reverse proxying features provided by web servers such as NGINX.

[1] https://medium.com/@madhukaudantha/microservice-architecture-and-design-patterns-for-microservices-e0e5013fd58a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM