This article is the second in a series of back-end microservice architectures. In microservice architecture, there are two common ways of communication between servicesRPC
and REST
。
The article is updated every week. Your “three companies” are my greatest affirmation. WeChat can search the public for the first time to read the official account of “backend Technology School” (usually one to two updates earlier than blogs).
About micro service and micro serviceRPC
For more details, please refer to the article I asked in my last interview: microservices, service governance, RPC, and next generation microservice framework… To help you understand it thoroughly!
What is the main content of this articleREST
Style design andRESTful
Interface. After reading this article, you will gain the following knowledge points:
- What is?
REST
andRESTful
-
REST
What is the interface design specification -
REST
Why design stateless - Is interface stateless really stateless
-
RPC
andREST
Applicable scenarios
Rest and restful
Rest (representational state transfer)
Is a software architecture style. Rest proposes a set of architectural constraints and principles that anyREST
The framework of constraints and principles is calledRESTful
framework.
Microservices need to communicate with each other to complete specific business processing. In a typical client server design model, client and server interact and cooperate through message request response,REST
It is such a set of design constraints and principle specifications for the interaction interface between microservices.
At first glanceREST
Every word of “expressional state transition” can be recognized without knowing what it means. No wonder this is the authorRoy Thomas Fielding
The concepts put forward in his doctoral dissertation are all academic terms, but those who are interested can go to see the original paper of the author, and I will post the address: https://www.ics.uci.edu/~fiel…
Today, lemon helps you understand this concept thoroughly in vernacular. Let’s break down the “expressional state transition” to find out what is “expressiveness” and what is “state transition”.
Expressiveness
In fact, “expressiveness” is lack of subject, and subject is “resource”. The complete description is resource expressiveness, that is, resource description. How to describe resources in network communication? Yes, it isUri (Uniform Resource Identifier)
。
Here are a few synonyms for you first popular science:
URI
Is a uniform resource identifier, used to uniquely identify a resource.
URL
Is a unified resource locator, which is a specificURI
, i.eURL
It can be used to identify a resource, and it also indicates how to locate the resource,URL
yesURI
A subset of.
URN
Unified resource naming is to identify resources by name.URN
So is itURI
A subset of.
stayHTTP
In the agreementURL
Identify resources, that is, the list of web addresses you see in the browser address bar.
Resource expressiveness
In order to illustrate the advantages of resource description interface design, let’s make a comparison of interface design methods.
Traditional interface design
Let’s take a look at the traditional network communication mode. hypothesislemon
The object of this character, in the server, is stored in a form ofc++
Ofclass
Type storage.
The following procedure shows that the client sends a request and the server creates alemon
Object.
- Server defined storage structure header file
lemon.h
class lemon{
string name;
string address;
uint64 phone;
}
- The client code refers to the server defined
lemon.h
,Cross referencing header files increases service coupling! - Client initializes a
lemon
The instance is sent to the server through the network interface after being serialized.
class lemon lm;
lm.name = "lemon";
lm.address = "Shenzhen";
lm.phone = 18666666666;
- The server receives the message, deserializes it, and stores the transmitted data
lemon
object
Resource expressive interface design
lemon
The internal objects of this service can be represented by a picture or includedlemon
Name, address, telephone number, etcxml
orjson
Format data representation.
{
name : "lemon",
address: "ShenZhen",
phone : 18666666666
}
<?xml version="1.0" encoding="UTF-8" ?>
<name>lemon</name>
<address>ShenZhen</address>
<phone>18666666666</phone>
in other words,lemon
The storage form of this “resource” in the service is invisible to the outside world. External clients can use different resource expression formats to obtain the resources of the server.
(if the server can speak, his heartos
It’s like this: the client doesn’t care how I save this object. As long as you say clearly what you want, just send a request.
The most obvious benefit of this is that the coupling between services is reduced. The client does not need to know the specific storage format of the resource in the server before accessing the service resource. It only needs to describe the resource form to modify, create, update and delete the server resource.
state transition
Now that you understand resource description, what is state transition? State transition means that the client drives the resource state of the server to change through a series of request actions. The state of the resource can be transferred between create modify view delete.
The macro response of resource state change is business process promotion. For example, you open an account in the banking system, check the balance, and close the account. In this process, you promote your bank account. This “resource” has experienced different state transitions, enabling you to complete different business operations.
Constraints for rest
Protocol selection
REST
It doesn’t mention what protocol should be used at the bottom. The most commonly used protocol in daily practice is based onHTTP
OfRESTful
realization.
that is becauseHTTP
Verbs that come with the agreementGET/POST/PUT/DELETE
It can be used as a method to push the state transitionHTTP
The standard status code is established. There are othersHTTP
Features that make theHTTP
Implementation aboveREST
It’s much simpler, and if you use other protocols, you need to implement these features yourself.
Request specification
RESTful
In the architecture, the state transition occurs in the “resource”, soURI
In general, it can only contain nouns representing “resources”, and is recommended to be pluralURI
A verb that operates on a resource.
On resourcesCurd "add, delete, modify and search"
The action should be in theHTTP
Of the request methodGET/POST/PUT/DELETE
It is embodied in.
Rest compliant writing method:
POST http://www.test.com/lemon //Create
Get http://www.test.com/lemon //Inquiry
PUT http://www.test.com/lemon //Modification
DELETE http://www.test.com/lemon //Delete
Writing method that does not conform to rest specification:
POST http://www.test.com/Createlemon //Create
POST http://www.test.com/Querylemon //Inquiry
POST http://www.test.com/Modifylemon //Modification
POST http://www.test.com/Deletelemon //Delete
Status code
The server message response carries the status code to instruct the client to process the next step. accord withRESTful
Standard interface return status codes are universal, and do not need additional conventionsHTTP status code status code
It represents the result of request processing and reduces the cost of interoperability between microservices.
Status code | Meaning of status code |
---|---|
2xx | Success, the operation was successfully received and processed |
3xx | Redirection, further action is required to complete the request |
4xx | Client error, request contains syntax error or cannot complete request |
5xx | Server error, the server encountered an error while processing the request |
Here are the common onesHTTP
Status code:
- 200 – Request successful
- 301 – resources (web pages, etc.) are permanently transferred to other URLs
- 404 – the requested resource (web page, etc.) does not exist
- 500 – internal server error
Stateless
RESTful
The interface requirement is stateless. Stateless means that any web request must be completely isolated from other requests. When the client initiates a request, the message itself contains all the information required by the server to identify the request context.
No state is not really no state
The “stateless” of the interface is more exactly stateless on the server side. The whole session still needs state maintenance. In order to complete a business process, the client and the server need to interact with each other many timesHTTP
The protocol is a “stateless protocol”, which requires the server to be able to identify several independentHTTP
Request status information to associate them with a business process.
Another example is the withdrawal of funds from the sub banking system
- In order to log in to the banking system, lemon needs to input the user name and password in the login page first, and then a login request is generated
- The server receives the login request, executes the login logic and returns the operation result
- After lemon logs in, he clicks to withdraw 1 million yuan and generates a withdrawal request
- The server receives the withdrawal request, executes the withdrawal logic and returns the operation result
There is a problem here. The server receives login request and withdrawal request at different time points, both of which are userslemon
If we don’t do it on a technical levelHTTP
If the request is associated, the server cannot know that the two requests are actually userslemon
Part of the “withdrawal business”.
Technical solutions
There are two technical solutions for the server to identify the “status information” of the request
-
Session
Methods. The server saves the session state, which is carried by the client every time it requestssession-id
。The server maintains a list of session state information and uses the
session-id
Uniquely identifies a status message,session-id
Generally included inHTTP
ResponsiveSet-Cookie
The header is returned to the client, and the subsequent client request carries thesession-id
Informativecookie
Header, server side parsingcookie
take outsession-id
To retrieve the status information corresponding to the message from the maintenance status list, so that the statelessHTTP
It becomes stateful.
-
Token
Methods. The server does not save the session state, and the client carries complete session state information (usually encrypted) to the server every time it requests.Token
Also known as “token” or temporary certificate signature, status information is encrypted totoken
This will decrypt every time the server receives a requesttoken
The status information corresponding to the request can be obtained, and different request messages can be associated with the same business processsession
This method has a similar effect, but this time the status information is not saved in the server.
The first of the above two implementationsSession
The way is stateful, the secondToken
The way is stateless.
If you want to make it happenRESTful
The interface is best implemented according to the second technical solution. Of course, there are other ways to realize stateless. The idea is “the server does not maintain session state”.
Why no state
In order to meet the requirements of high availability and load balancing, multiple micro services are distributed and clustered by load balancing, each service in the cluster is independent and peer-to-peer. If the server is unavailable or down when receiving the client request, stateless requests can be processed and responded by any other available server, which is very important in distributed applications.
Imagine that if the server keeps the state, every request in a transaction must be handled by the same server, which will lose the significance and advantage of distribution.
So,RESTful
The interface requirement is stateless in order to better adapt to distributed business scenarios and play the advantages of microservice cluster.
Rest and RPC
These two concepts often appear in microservice architecture design,REST
It is a software architecture interface design style,RPC
It is a kind of computer communication protocol. It seems to be two different concepts. If we want to compare them together, I prefer to put them togetherREST
Materialized into a kind ofHTTP
And in accordance withREST
The communication protocol of constraint design can be compared between the two communication protocols.
RPC in retrospect
RPC (Remote Procedure Call)
Remote procedure call is a computer communication protocol. Our general program calls are local program calls,RPC
It allows you to call another program’s function just like calling a local function, which involves network communication and interprocess communication, but you don’t need to know the implementation details,RPC
The framework blocks the underlying implementation for you.RPC
It’s a server clientClient/Serv er
Pattern, the classical implementation is a system of information interaction by sending request and receiving response.
Applicable scenarios
quite a lotRPC
The message transmission provided by the framework is based on binary, such asThrift
、Protocol buffers
。 The advantage of this method is that the message structure is relatively compact, and it can significantly reduce the network overhead for the application scenarios with frequent calls or large traffic and low delay requirements; another constraint is that someRPC
The framework has strong technical coupling, such asDubbo
Can only be used forjava
Technology stack. In conclusion,RPC
It is more suitable for efficient communication between micro services in the system.
RESTful
The interface is based onHTTP
OfREST
Design standard, onlyweb
Framework supportHTTP
Protocol and designRESTful
It is convenient to access and call third-party services,Interface design standards suitable for external exposure of microservice systems.
Write it at the end
This paper is a small aspect of interface selection in the design of microservice architecture. Many people will think that job interview, whether it is a large factory or a small company, is interviewing to build an airplane and screw up the work. I think that even if you can’t get in touch with the work of architecture, you should have a heart of architecture and highly determine cognition. If you only stare at the screw in your hand, what is the difference between it and salted fish?
Old rules. Thank you for your reading. The purpose of this article is to share your understanding of knowledge. I will repeatedly verify technical articles to ensure accuracy to the greatest extent. If there are obvious mistakes in the article, please point out that we can learn together through discussion.
Well, that’s all for today’s technology sharing. This article is the second part of the back-end development microservice design series. This series should continue to be updated. See you next time.
My more wonderful articles:
Very detailed Linux C / C + + learning route summary! Offered by Tencent
Linux “process” problems do not panic, senior programmers teach you 6 moves to deal with!
Interviewer: are you familiar with MySQL affairs? Let me ask you 10 questions
I used big data to analyze the recruitment needs of more than 1000 jobs in first tier cities, and told you how to find a job scientifically
Tencent background development interview written C + + knowledge points reference notes
Can you still play like this? I use vscode to draw class diagram, flow chart, sequence diagram, state diagram, not too cool!
Interviewer: how many redis distributed locks do you know? I can do three!
The most detailed personal blog tutorial building tutorial githubpages + Jekyll simple style blog
It’s not easy to create. Just like it, pay attention to it and support it
You can search the official account of WeChat for “back end technology school” to reply to “information”. Articles are updated every week, see you next time!