If the talk does not understand Spring Cloud core components, then I compiled this story white

These days can be really hot, ah, soak seaweed is better. The play was in full swing, suddenly stumbled on an undercurrent foot, then I have been rotating rotation in the water ... finally a black eyes.

The magic of love going round in circles. I crossed.

Neighboring sea, just a few kilometers can hear the voice, the people to never in contact. The world is small princes to cut to pieces, pot mess.

The reality is that my country because of the perennial war, leaving many women, marrying the other party needs to get through the channel; and A country rich grow as big as a pig and mouse, sold well. They can be made into the skin cloak, used for heating. Therefore, communication is inevitable.

The reality is this:
a, A State B State does not know of where herders often holding a treasure map like rags, buried in the rugged mountain road.
Two, B country C country do not understand spit the word vague, feel they are in distress, and so nearly ran to see, but found that in fact BS-ing.
Three, C pumpkins produced in the country to know the country sold to D, and the rest are rotten in the ground, E States began to eat the bark.
Four, F States have made known, but the influx of refugees in all directions, so they are very distressed. Among them, the refugees G country, most are bad.
Fifth, there have been other messengers continental plates, five years to no avail. See God porridge status of the land, for the poem: "TM really mess."

As a person crossing a pity beings left people. I want to leave this world a blueprint, so that future generations remember my name: xjjdog. At the same time, I think, why do I have this such a strong self-confidence.

"Memories" segment brought me back to the 21st century.

First, I want to talk about something technical: the single application

We have just started the service, in fact, not that complicated. I have only one machine configuration is very low, my applications, my code, my intelligence, all this in a small project inside. Since I was engaged in it, so my project name is called jisuanji. Some people say I do the project name in Chinese pinyin, too that. I do not listen, I was so named. I also called public module gg, call the password field mm, who tube wear it.

Yes, look at the following chart, is that simple. Project can live up to use nginx load balancing to do this step, even a small success.

This time, all the code is a whole, what user access, direct me to that.

Second, I split into two services

I may be like me, a little more than two people, I visited the project is growing, perhaps it is called like-minded. My own development speed, falling short of mind idea, it's time to recruit individuals to split the service.

Not too far removed, so the beginning, I jisuanjisplit into two services. Where the service B, only the deployment of a node, because it's not too much pressure. Even so, I had to buy 3 servers to deploy the service node, really heartache. I am so stingy man, of course, shared database. Although sometimes the machine pressure a bit big, but yet people die.

This time I was faced with a choice: how to access the service A service B do?
Since I webservice been engaged for some time, first thought of it. But this thing is too heavy, I might as well be comfortable accessed via Http. By HttpClient, or OkHttp, my service A, can now directly simulated Http request to access the service B.

When the second person team, began Tucao my project. Here's what he listed, guilt of my project: 1, complexity is too high, the code seriously coupling; 2, multi-technical debt, racking our brains demand a laundry list; 3, the code is not standardized, a lump of feces; 4, technological innovation difficult , a class of thousands of lines ...

For what? From a service split into two, so I Tucao. But in order to be able to split out hundreds service, I do put up with this feeling, after all my people are quite open-minded.

Third, the 乱成一锅粥

Such as a look at the past six months, boy, I removed the service to dozens. When my companion put a system configuration diagram showed me, I direct the ignorant force. I picked up nine service can see, drew a map.

First conducted business split. Such as payment services, business orders, the user center, shopping center, have set up a separate team. Each business segment has been split into different services.

In between, were the following changes:
First, a small partner wrote a generic call HttpClient component own load balancing strategy.
Second, there is another small partner, habits protobuf, so chose gRPC.
Third, SOA is still proved there is a market, which is not, there is the introduction of interactive webservice several services.
Fourth, some people want to use RMI, I was to discover, veto, stillbirth in the abdomen.
Fifth, each build a new service, we need to update the look excel, then this will excel well known out.

Now the whole system, is simply a grotesque. What means of communication are, what the interactive format is not missing. Take the most terrible D services, the optical communication module, 20 on the introduction of several jar package. If the application scale to thousands ... My god ...

Even worse is that so many services on the line every module are scared, because it does not know what in the end there will be a chain reaction.

It's time to call out the super fly Xia. Oh no, call out the micro-services.

Fourth, the micro-service strikes

Currently, the hottest micro-services framework that is SpringCloud up. Although netflix company for the maintenance of certain components often miss it, but some core components is still very classic.

1, Registration Center: Eureka

Service A, how to find the service B, there are many ways. For example, you live in a small town, you ask who xjjdog that Pharaoh might know him, but Mike could not know; but Wang Li know, so he eventually could find by xjjdog, but some trouble.

You can easily pull a person in town to ask who xjjdog Yes. You will magically come up with a little book, the people you know and tell them. When you ask the brain-dead style of a pass in the end everyone knows xjjdog up.

The above said is gossip protocol. Ultimately, you are able to know each other, as are the big mouth. For example, Xiao Zheng had a baby, not too much time, the whole town of people put the child in the book of records.

In this way, the service will be able to know each other, to complete the communication.


Unfortunately, this is not nice, went from the western end of the east end of town, it takes a long time. At this time, probably because of the small Zheng Gangsheng child congenital disease died. We need a higher concentration of information and effective manner.

This requires a center, where the information is authoritative. In SpringCloud system, the most common registry is Eureka. After any service starts, it registers itself to Eureka registry; when the service of death, will notify Eureka.

Thus, when the service A service B're looking for, just ask Eureka Server on it, it knows everything.

To this end, it had to have part of the workload. Let us look at the figure below. This registration action, is a component called Eureka Client to complete. Service startup and shutdown time, will sell themselves through this component; and when you want to call the service A service B, directly asked Eureka Server on it. After the service A to get the result, it will result in a cache in the local registry.

You can think of a copy. So after Eureka Server die, it does not affect the service A service to find B.

2, load balancing components: Ribbon

Now comes the question. A list of examples to get the service after service B, found two.

10.0.0.12
10.0.0.16
复制代码

Then trouble, which machine the tune it? This is SpringCloud role Ribbon components. In fact, Round Robinit is a general-purpose computer terminology. It is the most commonly used load balancing strategy, the request will be evenly allocated to each server behind.

When Ribbon work, do the following four things:
1, preference in Zone and a less loaded Eureka Server, to connect.
2, regular updates from Eureka, filtering services and instances list.
3, according to the load balancing policy, choose a real example of an address from the registry.
4, by RestClient initiate a call to the service.

It can be seen behind the Ribbon, or Http protocol used to interact. Look at the following code, you can call directly implement the remote service.

@Bean
@LoadBalanced
RestTemplate restTemplate(){
    return new RestTemplate();
}
...

 @Autowired
RestTemplate restTemplate;
public String test() {
    return restTemplate.getForObject("http://test-service/test", String.class);
}
复制代码

Filter the Ribbon looks test-service, and replaced with the corresponding address of the instance.

Policy Ribbon not only provides polling strategy, there are other, such as:
1, a random the Random
2, the response time weighted
3, Custom

Take polling, the final selection logic in RoundRobinRule class.

private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % modulo;
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
}
复制代码

3, to simplify the code born: Feign

You can see, Ribbon need to build their own http requests, simulate http request is then sent to other services using RestTemplate, steps quite tedious. And the return type of insecurity, but also not express what semantics.

In fact, through Ribbon way, we have been able to complete calls between the micro-services. But SpringCloud development language is Java, sure to be a more advanced package, in order to reflect its force grid.

Feign Thanks to Java's dynamic proxy mechanism, the final package a set of simple invocation interface methods will need to call other services defined as abstract methods, do not need to build their own http request.

First, Feign based @FerignClient annotation, dynamic proxies, to create a dynamic proxy class. Next, you just call interface by the way, you can construct Ribbon call parameters mentioned above, this process will be automatically populated. Finally, Ribbon configuration request initiated by the real call, and returns the value reflected by the assembly.

So, Feign only skin, eventually to be called via Ribbon. In my opinion, the Ribbon and Feign into one component, is reasonable.

They have a more generic term, it is called RPC (Remote call).

4, abnormal umbrella: Breaker

Below a payment request, for example, talk about the case is not calm, the service would react.

Every true payment request, will call the other four services. First, the authentication service obtains the user's authority to pay; then, risk control services will do some validation rules; in order to better promote their products, marketing business calls, get some recommendation information; finally, calls polymerization payment service, genuine payment.

Among them, in fact, is dispensable marketing business. Allowing users to spend out first of all, it is our top priority.

Consider the following scenario, marketing business due to system failure or load problems, there is a major area of ​​unavailable or timed out. Then, all requests are stuck in the acquisition of marketing information code.

As shown, the authentication control wind have been passed. Because a bypass function: marketing business, resulting in the payment can not be true. This time, if someone calls the payment request, you will find the payment request is also finished.

Because they end up stuck in the marketing section of this small code.

So, for essential business marketing service provider that is not a link, there must be a means to make it in the event of problems, isolate it for some time.

Component is responsible for this function is called Hystrix.

With our program of thinking, this is an if condition.

if(服务发生问题){
    return "暂时不要处理";
}
复制代码

But we can not be so encoded in the business code. So Hystrix for each service opened a thread pool, and there are more complex rules to control the behavior of these problems of the service. For example, in 2 minutes, return to the default direct marketing business results, rather than been stuck there.

This process, called blown. Like power, out of the question, first cut off the fuse, do not take appliances to burn.

5, nor that this gateway Gateway: zuul

API Gateway is a reverse 路由, it shields the interior details, provides a unified entrance to the caller. Gateway, in fact, a bunch 过滤器of geometry, and can achieve a series of business unrelated cross-section of functions.

Familiar Spring AOP knows a function, the route is a AOP for distributed services.

Let me talk a gateway or duties under it. Simple list a few:
1, safety certification. It provides a unified authentication and authorization functions to avoid duplication of development.
2, fusing, current limiting. For service problems, carry out blowing operation; the traffic forecast, restrict access.
3, log monitoring. Unified entrance flow, traffic analysis and monitoring.
4, shielding the details of the internal and external to provide a consistent interface.
5, to achieve gray scale. Using a custom strategy to achieve diversion, to achieve the purpose of the test.

Gateway location, it generally follows FIG.

We can see, we usually use nginx, it can be used as a gateway. But for micro-services is, nginx configuration is too much trouble. Not to say nginx is not powerful enough, but because they are not a system, there is integration costs (such as kong).

zuul not the case, and other components SpringCloud it is like family. The family, of course, will be special care. Zuul itself is a Servlet, after external requests through a series Filter, will achieve true service. The above said fuse is highly integrated.

6, a polymerization FIG.

With the key components of the above, things more clear. We put it on a graph, is the following way.

We simplify it a bit, you can get a more concise map. It can be seen only need three key points:
1, service registry, unified management of all information services, default component is Eureka.
2, RPC, network communication components, how to call service A service B. In SpringCloud in, it is Ribbon + Feign.
3, Gateway, split expose how service interfaces, and ultimately to see people look. Default components are Zuul.

Journey

Make sense

Things chaotic process, the most effective way, is the centralization and decentralization. The core is centralized and decentralized authorization or approval, or doomed to failure. Authorization is on, you should agree with my approach those in power, so I need to use and understand language, to persuade them to accept this system; identity, is the next best is from the people's complaints, issued improvement measures, so authoritative professional.

Micro and services, the need to give some of the old concepts, forcibly giving natural-looking new meaning. For example, I put a unified language called cultural integration, it is tall some.

The second is the responsibility of the demolition fine enough. Fine enough to be able to fine people at each location in order to carry out their duties.

Another point, the whole process can be systematized, can be deduced. If one thing has unpredictable consequences, it is the adventurer to do.

Some ways

In order to carry out a preliminary understanding of the world, I set up a resource statistics department of mountains and rivers conducted a preliminary investigation, rule-drawn map. Social relations and the current situation of the complex carried out thoroughly. I publish this information into books, it was a treasure map collectors of jealousy and hatred. They hide in unknown corners, dirty act.

I also chose a nice feel dialect, unified the language of each vassal state. In the process of implementation in many times by the natives strong opposition, they refuse to correct it. I beheaded after being forced to a few, after the implementation, it is much faster.

For all important commodities, were centralized control. The world is not a precious gold, but the food, so I also built roads and pervasive trading center easily accessible. Since then, very few starve extraordinary. Since this part is within my control, so it is carried out smoothly.

G is relatively sturdy country folk, violence often occur. This inevitably, from the beginning, this country would be difficult to domestication. Fortunately, they are missing, the system can cycle down. Not long ago, the country took place in G major events, all other countries boycott, G-country nationals prohibit the entry. But time is to resolve the pain medicine, I estimate that such restrictions will not last long.

But dross is still there. Some places, there are rivers and lakes, there is oppression. But such dross I do not want other people to see. Visiting messenger, you should only be able to see songs and dances, live and work, which doomed them and not let the bottom of the contact, or to find the current situation in which the fair without foul.

Diplomats and their joy of playing, I am very pleased.

End

I clearly know that in order to build a harmonious nature of the system, had spent much of the cost. This is one part, and not always perfect run. Moreover, in this seemingly peaceful overall, it is the breeding ground for countless other headaches, but that's another topic.

That's it. Everything I did, all my expectations, just to: when new opportunities behind me, I was able to calm, magnificent turn.

This is my day to be able to pass through, ready made.


Not good enough? Focus on micro-channel public number xjjdog, there are more companion and dry goods.

Guess you like

Origin juejin.im/post/5d4296ffe51d4562043f5682