Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the entry-level knowledge points of Spring Cloud

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces in detail "what are the introduction to Spring Cloud knowledge points", the content is detailed, the steps are clear, and the details are handled properly. I hope this article "introduction to Spring Cloud knowledge points" can help you solve your doubts.

What is Spring cloud?

Building a distributed system does not need to be complex and error-prone. Spring Cloud provides a simple and acceptable programming model for the most common distributed system patterns to help developers build resilient, reliable, and coordinated applications. Spring Cloud is built on top of Spring Boot, making it easy for developers to start and quickly apply it to production.

The official is sure enough, the introduction is so organized.

The Spring Cloud I understand is the one-stop solution of the micro-service system architecture. In the process of building micro-services, we need to do operations such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring and so on. Spring Cloud provides us with a set of simple programming model, which enables us to easily build micro-service projects on the basis of Spring Boot.

The version of Spring Cloud

Of course, this is just a digression.

The version number of Spring Cloud is not the numerical version number we usually see, but some very strange words. These words are the names of London subway stations in England. At the same time, it corresponds to the chronological order of the versions according to the alphabetical order, for example: the earliest Release version Angel, the second Release version Brixton (British place names), followed by Camden, Dalston, Edgware, Finchley, Greenwich, Hoxton.

Spring Cloud's Service Discovery Framework-- Eureka

Eureka is a REST (representative state transition)-based service, which is mainly used for location services in the AWS cloud to achieve load balancing and failover of middle-tier servers. We call this service the Eureka server. Eureka also comes with a Java-based client component, Eureka Client, which makes it easier to interact with services. The client also has a built-in load balancer that can perform basic circular load balancing. At Netflix, more complex load balancers wrap Eureka to provide weighted load balancing based on a variety of factors such as traffic, resource usage, error conditions, and so on, to provide excellent resilience.

In general, Eureka is a service discovery framework. What is service and what is discovery?

To give an example of life, for example, we usually rent a house to find an intermediary.

When there is no intermediary, we need a landlord to find out whether there is a house for rent, which is obviously very laborious. One is that you can't find a lot of housing for you to choose from with one person's ability. Moreover, you don't bother to go on looking like this (after looking for so long, there is nothing suitable but to make do with it). Here we are the Consumer of the microservice, and the landlords are the Provider of the microservice. The consumer Consumer needs to invoke some of the services provided by the provider Provider, just as we now need to rent their house.

But if it is only between the tenant and the landlord, their efficiency is very low. The landlord can't find the tenant, the tenant can't make money, and the tenant can't find the landlord to live in. So, later, the landlord must have thought of broadcasting his own housing information (such as posting small advertisements on the street), so that for the landlord, he had done his job (publishing the housing), but there were two problems. First, other people who are not tenants can receive this kind of rental news, which is nothing in the real world, but there will be a problem of resource consumption in the computer world. Second, it is still very difficult for tenants to find you. Imagine that I need to rent a house. I also need to find small advertisements on the street one by one. Is it troublesome?

What are we going to do? Of course, we will not be so stupid, the first time is to find an intermediary, it provides us with a place for unified housing, we consumers just need to go to it to find it. As for the landlord, they only need to release the property in the intermediary.

So now, this is our model.

However, there will be some problems at this time.

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

What if the landlord doesn't want to sell the house after registration? Do we need to get the landlord to renew the contract regularly? If the landlord does not renew the contract, do you want to remove them from the registration list of the intermediary?

Do tenants also have to register? Otherwise, how can Party B come to the contract?

Can an intermediary be a chain store? If this store cannot be used because of some force majeure, can we change to another chain store?

In view of the above problems, let's reconstruct the above pattern diagram.

All right, finish this? Let's take a look at some of the basic concepts of Eureka, and you'll see why it's so simple to understand. ?

Service discovery: in fact, it is an "intermediary", and there are three roles in the whole process: service provider (rental house), service consumer (tenant), service intermediary (housing intermediary).

Service provider: is to provide some services that you can perform to the outside world.

Service consumers: "users" who need to use some services.

Service intermediary: in fact, it is a "bridge" between service providers and service consumers, service providers can register themselves with service intermediaries, and service consumers can find service providers registered in service intermediaries if they need to consume some services (using some functions).

Service Registration Register:

Official explanation: when an Eureka client registers with Eureka Server, it provides its own metadata, such as IP address, port, health indicator URL, home page, etc.

Combined with intermediary understanding: the landlord (provider Eureka Client Provider) registers with the intermediary (server Eureka Server) information about the house, such as area, price, location, and so on (metadata metaData).

Service Renewal Renew:

Official explanation: Eureka customers will send a heartbeat every 30 seconds (by default) to renew their contract. Inform Eureka Server that the Eureka customer still exists and that there is no problem by renewing the contract. Normally, if Eureka Server does not receive a renewal from the Eureka customer within 90 seconds, it removes the instance from its registry.

Combined with intermediary understanding: the landlord (provider Eureka Client Provider) regularly tells the intermediary (server Eureka Server) that my house is rented (renewed), and the intermediary (server Eureka Server) continues to keep the house after receiving it.

Get the registration list information Fetch Registries:

Official explanation: the Eureka client gets registry information from the server and caches it locally. The client uses this information to find other services for remote invocation. The registration list information is updated periodically (every 30 seconds). Each time the registration list information is returned may be different from the cache information of the Eureka client, which is automatically processed by the Eureka client. If, for some reason, the registration list information does not match in time, the Eureka client will retrieve the entire registry information. The Eureka server caches the registration list information, the entire registry and the information of each application are compressed, and the compressed content is exactly the same as the uncompressed content. Eureka clients and Eureka servers can communicate using JSON / XML format. By default, the Eureka client uses the compressed JSON format to obtain information about the registration list.

Combined with the intermediary understanding: the tenant (consumer Eureka Client Consumer) goes to the intermediary (server Eureka Server) to get all the housing information list (client list Eureka Client List), and the tenant will regularly get and update the local list from the intermediary (server Eureka Server) in order to get the latest information.

Service offline Cancel:

Official explanation: the Eureka client sends a cancellation request to the Eureka server when the program is closed. After the request is sent, the client instance information is deleted from the server's instance registry. The offline request will not be completed automatically, it needs to call the following: DiscoveryManager.getInstance (). ShutdownComponent ()

Combined with intermediary understanding: the landlord (provider Eureka Client Provider) tells the intermediary (server Eureka Server) that my house is no longer rented, and the intermediary then removes the registered housing information from the list.

Remove Eviction from the service:

Official explanation: by default, when the Eureka client does not send a service renewal for 90 seconds (3 renewal cycles) to the Eureka server, that is, the heartbeat, the Eureka server will delete the service instance from the service registration list, that is, the service will be removed.

Combined with intermediary understanding: the landlord (provider Eureka Client Provider) will regularly contact the intermediary (server Eureka Server) to tell him that my house will be rented (renewed). If the intermediary (server Eureka Server) does not receive information from the provider for a long time, then the intermediary will remove his house information (service removal).

Here is the Eureka architecture diagram officially given by Netflix, and you will find that it is no different from the mediation diagram we drew earlier.

Eureka architecture diagram

Of course, there are many components that can act as service discovery: Zookeeper, Consul, Eureka, and so on.

More information about Eureka (self-protection, initial registration strategy, etc.) can be found on the official website.

Ribbon of load balancer

What is RestTemplate?

Isn't it about Ribbon? Why are we talking about RestTemplate? Don't worry, listen to me slowly.

I won't listen.

I'm just saying! RestTemplate is a client class provided by Spring that accesses Http services. That is, RestTemplate is used for calls between microservices. For example, at this time, we, Consumer B, need to invoke the services provided by provider A. that's what we need to write. Such as my pseudo code below.

@ Autowired private RestTemplate restTemplate; / / this is the ip address of provider A, but if Eureka is used, it should be the name of provider A private static final String SERVICE_PROVIDER_A = "http://localhost:8081"; @ PostMapping (" / judge ") public boolean judge (@ RequestBody Request request) {String url = SERVICE_PROVIDER_A +" / service1 "; return restTemplate.postForObject (url, request, Boolean.class);}

If you are interested in the source code, you will find that the registration, renewal and so on in the Eureka framework we mentioned above are all RestTemplate used at the bottom.

Why do I need Ribbon?

Ribbon, an open source load balancing project of Netflix, is a client / in-process load balancer that runs on the consumer side.

Let's take another example, for example, we have designed a second kill system, but for the high availability of the whole system, we need to build a cluster of the system, and at this time we consumers can have multiple ways to call the second kill system, as shown in the figure below.

If we do not do some equalization operations at this time, if we make a large number of calls to the second kill system 1, and the other two basically do not request, it will cause the second kill system 1 to crash, and the other two will become puppets. So why do we have to do clusters, and what is the point of our high availability?

So Ribbon appears, and notice that the bold words above us-- run on the consumer side. I mean, Ribbon is a load balancer that runs on the consumer side, as shown in the figure below.

Its working principle is that after the Consumer side obtains all the service lists, it uses the load balancing algorithm internally to call multiple systems.

Comparison between Nginx and Ribbon

When it comes to load balancing, we have to mention the famous Nignx, which, unlike Ribbon, is a centralized load balancer.

What is centralization? The simple understanding is to centralize all requests and then load balance. As shown in the following picture.

We can see that Nginx receives all requests for load balancing, while for Ribbon it is load balancing on the consumer side. As shown in the following picture.

Please note the location of the Request. In Nginx, the request is first entered into the load balancer, while in Ribbon, the request is first made on the client side.

Several load balancing algorithms of Ribbon

Load balancing, both Nginx and Ribbon need the support of their algorithms, and if I remember correctly, Nginx uses polling and weighted polling algorithms. However, there are more load balancing scheduling algorithms in Ribbon, and the default is the RoundRobinRule polling strategy.

RoundRobinRule: polling policy. The policy adopted by Ribbon by default. If an available provider is not found after a round of polling, the maximum number of polls is 10. If it is not found in the end, null is returned.

RandomRule: random policy, randomly selecting one of all available provider.

RetryRule: retry the policy. First obtain the provider according to the RoundRobinRule policy, and if the acquisition fails, try again within the specified time limit. The default limit is 500 milliseconds.

There are many more, not one by one here. The most important thing you need to know is the default polling algorithm, and you can change the default load balancing algorithm by making changes in the configuration file.

ProviderName: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

Of course, in Ribbon you can also customize the load balancing algorithm, you just need to implement the IRule interface, and then modify the configuration file or customize the Java Config class.

What is Open Feign?

With Eureka,RestTemplate,Ribbon, we can. We are happy to make inter-service calls, but it is still not convenient to use RestTemplate, which we make every time.

@ Autowired private RestTemplate restTemplate; / / this is the ip address of provider A, but if Eureka is used, it should be the name of provider A private static final String SERVICE_PROVIDER_A = "http://localhost:8081"; @ PostMapping (" / judge ") public boolean judge (@ RequestBody Request request) {String url = SERVICE_PROVIDER_A +" / service1 "; / is it too troublesome? Url, request, and return type return restTemplate.postForObject (url, request, Boolean.class) each time;}

Is it too troublesome to call RestRemplate's API every time, and can I make calls between services as I did with the original code?

Smart kids must have thought of it, so use mapping, just like domain name and IP address mapping. We can map the invoked service code to the consumer side so that we can "develop seamlessly".

OpenFeign also runs on the consumer side and uses Ribbon for load balancing, so OpenFeign has built-in Ribbon directly.

After importing Open Feign, we can happily write Consumer-side code.

/ / use the @ FeignClient annotation to specify the name of the provider @ FeignClient (value = "eureka-client-provider") public interface TestClient {/ / be sure to note that you need to use the request relative path on the provider side, which is equivalent to mapping @ RequestMapping (value = "/ provider/xxx", method = RequestMethod.POST) CommonResponse getPlans (@ RequestBody planGetRequest request);}

Then we can call it in Controller as we used to call the Service layer code.

@ RestController public class TestController {/ / this is equivalent to the original auto-injected Service @ Autowired private TestClient testClient; / / controller calling the service layer code @ RequestMapping (value = "/ test", method = RequestMethod.POST) public CommonResponse get (@ RequestBody planGetRequest request) {return testClient.getPlans (request);}}

Indispensable Hystrix

What is the breaker and downgrade of Hystrix

In a distributed environment, it is inevitable that there are some failures in many service dependencies. Hystrix is a library that helps you control interactions between these distributed services by adding wait time tolerance and fault-tolerant logic. Hystrix does this by isolating access points between services, stopping cascading failures between services, and providing backup options, all of which can improve the overall resilience of the system.

Generally speaking, Hystrix is a library that can be fused and degraded, and the resilience of the whole system can be improved by using it.

So what is circuit breaker and demotion? For another example, at this time our entire microservice system is like this. Service An invokes service B, and service B invokes service C, but for some reason, service C is overwhelmed, and a large number of requests are blocked at service C.

It's a good thing Service C is blocked, after all, it's just a system crash. Note, however, that at this time, because service C cannot return a response, the request of service B to invoke service C will block, similarly, service B will block, and service A will also block and crash.

Please note why the blockage crashes. Because these requests will consume the threads, IO and other resources of the system, the system server will collapse after consuming you.

It's called a service avalanche. Mom, you haven't explained the above two breakers and demotions to me. What kind of service avalanche are you giving me now?

Don't worry, listen to me slowly.

The so-called circuit breaker is an effective solution to the service avalanche. When the request failure rate within the specified time window reaches the set threshold, the system will directly disconnect the request link through the circuit breaker.

That is, the above service B calls service C within the specified time window, and the failure rate of the call reaches a certain value, then Hystrix will automatically cut off the requests between service B and C, so as to avoid causing service avalanche.

In fact, the circuit breaker mode mentioned here refers to the circuit breaker mode in Hystrix. You can use the simple @ HystrixCommand annotation to mark a method, so that Hystrix will use a circuit breaker to "wrap" this method. Whenever the call time exceeds the specified time (default is 1000ms), the circuit breaker will interrupt the call to this method.

Of course, you can set many properties of this annotation, such as setting the timeout, like this.

HystrixCommand (commandProperties = {@ HystrixProperty (name = "execution.isolation.thread.timeoutInMilliseconds", value = "1200")}) public List getXxxx () {/ /. Omit code logic}

However, I checked some blogs and found that they all confused the concepts of circuit breaker and demotion, which, as I understand it, is for a better user experience when a method call is abnormal. Give a user-friendly response by executing another kind of code logic. This corresponds to the backup processing mode of Hystrix. You can set alternate code logic for a method by setting fallbackMethod. For example, if a hot news appears at this time, we will recommend it to the user to check the details, and then the user will query the details of the news through id. However, because the news is too hot (such as what is easy to see recently), a large number of users visiting at the same time may cause the system to crash, so we will downgrade the service. Some requests will be downgraded, such as the current number of people is too large, please check later, and so on.

/ / specify the backup method call @ HystrixCommand (fallbackMethod = "getHystrixNews") @ GetMapping ("/ get/news") public News getNews (@ PathVariable ("id") int id) {/ / call the news system to get the news api code logic omitted} / / public News getHystrixNews (@ PathVariable ("id") int id) {/ / downgrade / / return the current number is too large, please check it later}

What is the rest of Hystrix?

I also came into contact with the concept of a bulkhead model while reading the book Spring Micro Services practice. Without using bulkhead mode, Service An invokes Service B, which is executed by default using the same set of threads, and when a service has a performance problem, all threads are maxed out and wait for processing work. At the same time, new requests are blocked, eventually causing the program to crash.

I recommend you to understand the specific principle. In this article, the bulkhead model is not explained too much. Of course, there is the Hystrix dashboard, which is used to monitor the index information of Hystrix in real time. Here, I will also throw out this question, hoping that those who do not know can search it by themselves.

Micro-service gateway-- Zuul

ZUUL is the front door for all requests from the device and web site to the back end of the Netflix streaming application. As a border service application, ZUUL is built for dynamic routing, monitoring, resilience and security. It also has the ability to route requests to multiple Amazon Auto Scaling Groups (Amazon Auto scaling Group, a cloud computing method of Amazon) according to the situation.

After learning about Eureka above, we know that service providers are accessed by consumers through Eureka Server, that is, Eureka Server is a unified entry for service providers. So how can users access these consumer projects when there are so many consumers in the application that need to be called by users? Of course, you can access these projects directly as before. However, there is no unified entry for consumer engineering calls in this way, so it is not easy to access and manage, and Zuul is such a unified entrance for consumers.

If you have studied the front end, you must know Router, such as routing in Flutter, routing in Vue,React, using Zuul, you will find that the routing function is basically the same as configuring routing in the front end. ?? I occasionally masturbate Flutter.

You should be familiar with the gateway. To put it simply, the gateway is the only external entrance to the system, which is between the client and the server. It is used for authentication, current restriction, routing, monitoring and other functions of the request.

Yes, Zuul basically has all the functions of the gateway. The most important thing in Zuul is routing and filter. In the official document, the title of Zuul is

Router and Filter: Zuul

Routing function of Zuul

Simple configuration

I wanted to copy some code for you, but after thinking about it, because the configuration of each code is relatively fragmented and looks fragmented, I decided to draw a diagram for you to explain it.

Please don't like me just because I'm so nice. Crazy hint.

For example, at this time, we have registered two Consumer and three Provicer with Eureka Server. At this time, we should add a Zuul gateway like this.

Emmm, there is a lot of information. Let me explain. I won't explain the previous knowledge.

First of all, Zuul needs to register with Eureka. What are the benefits of registration?

You are silly, Consumer has registered with Eureka Server, my gateway can get all the Consumer information as long as I register?

What's the advantage of getting the information?

Can I get all the Consumer metadata (name, ip, port) when I get the information?

What are the benefits of getting this metadata? If we get it, can we just do the route map? For example, when the original user calls the interface localhost:8001/studentInfo/update of Consumer1, can we call it this way? what about localhost:9000/consumer1/studentInfo/update? Are you suddenly enlightened?

The url here does not use restful style in order to make more people understand it.

If you understand the above, then you can understand the most basic configuration of Zuul. See below.

Server: port: 9000 eureka: client: service-url: # all you have to do here is to register Eureka defaultZone: http://localhost:9997/eureka

Then add the @ EnableZuulProxy annotation to the startup class. Yes, it's that simple.

Unified prefix

This is very simple, that is, we can add a uniform prefix, for example, we just called localhost:9000/consumer1/studentInfo/update, this time we add the following in the yaml configuration file.

Zuul: prefix: / zuul

So we need to access it through localhost:9000/zuul/consumer1/studentInfo/update.

Routing policy configuration

You will find that the previous access method (directly using the service name), the need to expose the micro-service name to the user, there will be security problems. Therefore, you can customize the path instead of the micro-service name, that is, the custom routing policy.

Zuul: routes: consumer1: / FrancisQ1/** consumer2: / FrancisQ2/**

At this point you can use localhost:9000/zuul/FrancisQ1/studentInfo/update for access.

Service name masking

Don't think you're ready at this time. You can try to use the micro-service name after you have configured the routing policy. You need to mask the service name at this time.

Zuul: ignore-services: "*"

Path masking

Zuul can also specify the masked path URI, that is, as long as the user request contains the specified URI path, the request will not be able to access the specified service. In this way, you can restrict the permissions of users.

Zuul: ignore-patterns: * * / auto/**

So we can filter out requests for auto.

* * means to match multi-level arbitrary paths

* means to match any path at the first level

Sensitive request header masking

By default, sensitive request headers such as Cookie and Set-Cookie are blocked by zuul. We can remove these default masks and, of course, add request headers to be masked.

Filtering function of Zuul

If the routing function is the basic operation of Zuul, then the filter is the weapon of Zuul.

Simply implement a request time log print

To implement our self-defined Filter, we just need to inherit ZuulFilter and add the filter class to the Spring container with the @ Component annotation.

Before I show you the code, let me explain some points for attention about the filter.

Filter type: Pre, Routing, Post. The pre-Pre is to filter before the request, the Routing route filter is the routing strategy we mentioned above, and the Post post-filter is the filter that filters before the Response. You can observe the above picture combined with understanding, and I will give the corresponding comments below.

/ / add Spring container @ Component public class PreRequestFilter extends ZuulFilter {/ / return filter type here is the pre-filter @ Override public String filterType () {return FilterConstants.PRE_TYPE } / / specify that the smaller the filter order, the first to execute first. Of course, the first execution is not really the first one in Zuul. Other filters will be executed first / / that is written to death, such as SERVLET_DETECTION_FILTER_ORDER =-3 @ Override public int filterOrder () {return 0. } / / when to filter / / here we can make some judgments so that we can filter out requests that do not comply with the regulations, etc. @ Override public boolean shouldFilter () {return true } / / what to do if the filter is allowed to pass @ Override public Object run () throws ZuulException {/ / here I set the global RequestContext and record the request start time RequestContext ctx = RequestContext.getCurrentContext (); ctx.set ("startTime", System.currentTimeMillis ()); return null }} / / lombok log @ Slf4j / / join the Spring container @ Component public class AccessLogFilter extends ZuulFilter {/ / specify the filter type of the filter / / this is the post filter @ Override public String filterType () {return FilterConstants.POST_TYPE } / / SEND_RESPONSE_FILTER_ORDER is the last filter / / our filter executes @ Override public int filterOrder () {return FilterConstants.SEND_RESPONSE_FILTER_ORDER-1;} @ Override public boolean shouldFilter () {return true before it. } / / Policy executed during filtering @ Override public Object run () throws ZuulException {RequestContext context = RequestContext.getCurrentContext (); HttpServletRequest request = context.getRequest (); / / get the original start time from RequestContext and use it to calculate the entire time interval Long startTime = (Long) context.get ("startTime") / / here I can get HttpServletRequest to get URI and print out String uri = request.getRequestURI (); long duration = System.currentTimeMillis ()-startTime; log.info ("uri:" + uri + ", duration:" + duration / 100 + "ms"); return null;}}

The above is a simple implementation of the request time log printing function, do you feel the power of Zuul filtering?

No? All right, let's do it again.

Token bucket current limit

Of course, it is not only the token bucket current limit mode, it can do as long as the Zuul is current limit work, here I am just a simple example.

Let me first explain what token bucket current limit is.

First of all, we will have a bucket. If it is not full, we will put tokens in it at a fixed rate. If a request comes, you must first obtain a token from the bucket. If you do not get it, the request will be rejected. If you get it, then let it go. It's very simple, ah, ha, ha,

Let's implement token bucket flow restriction through the pre-filter of Zuul.

@ Component @ Slf4j public class RouteFilter extends ZuulFilter {/ / defines a token bucket that produces 2 tokens per second, that is, a maximum of 2 requests per second private static final RateLimiter RATE_LIMITER = RateLimiter.create (2); @ Override public String filterType () {return FilterConstants.PRE_TYPE;} @ Override public int filterOrder () {return-5 } @ Override public Object run () throws ZuulException {log.info ("release"); return null;} @ Override public boolean shouldFilter () {RequestContext context = RequestContext.getCurrentContext (); if (! RATE_LIMITER.tryAcquire ()) {log.warn ("traffic overload") / / specify that the current request failed to filter context.setSendZuulResponse (false); / / return response code 429 to the client, with too many requests context.setResponseStatusCode (429); return false;} return true;}}

Do you think it's cool that we can limit the number of requests to two in a second?

Other things about Zuul

Zuul's filter certainly has more than the two functions I implemented above, it can also implement permission verification, including the grayscale publishing I mentioned above, and so on.

Of course, there must be a single point of problem with Zuul as a gateway. If we want to ensure the high availability of Zuul, we need to configure the cluster of Zuul. At this time, we can use some additional load balancers such as Nginx.

Spring Cloud configuration Management-- Config

Why use it for configuration management?

When our micro service system starts to grow up slowly, then many Consumer, Provider, Eureka Server and Zuul systems will have their own configurations. At this time, we may need to change the configuration of some applications while the project is running. If we do not manage the configuration uniformly, we can only go to the next one of each application to find the configuration file and then modify the configuration file and restart the application.

First of all, for the distributed system, we should not go to each application to modify the configuration file separately, and for restarting the application, the service is inaccessible, so we directly abandon the availability, which we do not want to see.

Is there a way to manage the configuration file uniformly and modify the configuration file dynamically while the project is running?

That's the Spring Cloud Config I'm going to introduce today.

Spring Cloud Config is not the only framework for configuration management, and you can choose according to your needs (disconf, Apollo, etc.). And for Config, there are some places that are not so satisfactory.

What is Config?

Spring Cloud Config provides server and client support for externalized configurations in distributed systems. Using the Config server, you can manage the external properties of applications in all environments in a central location.

To put it simply, Spring Cloud Config means that the configuration files of each application / system / module can be stored in a unified place and then managed (Git or SVN).

If you think about it, our application will only load the configuration file when it starts, then our Spring Cloud Config will expose an interface to the launch application to get the configuration file it wants, and the application will get the configuration file and initialize it. Just like the picture below.

Of course, you must also have a question here: if I change the corresponding configuration file in the remote configuration repository (Git) while the application is running, will the launched applications that depend on this configuration file make their corresponding configuration changes?

The answer is no.

What? So how do you modify the configuration file dynamically? Isn't this a configuration drift? You scumbag? you lied to me again!

Don't worry, you can use Webhooks, a feature provided by github, which ensures that the configuration information in the client is updated after the remote library's configuration file is updated.

Oh, that's more like it. I'll check how to use it.

Wait a minute, hear me out. Webhooks can solve it, but you will find that it is not suitable for production environment at all, so you will not use it at all.

In general, we will use Bus message bus + Spring Cloud Config for dynamic refresh of configuration.

Lead to Spring Cloud Bus

An event bus used to link services and service instances to a distributed messaging system. It is useful to propagate state changes in a cluster (such as configuration change events).

You can simply understand that the role of Spring Cloud Bus is to manage and broadcast messages in distributed systems, that is, the broadcast mode in message engine systems. Of course, Spring Cloud Bus, as a message bus, can do a lot of things, not just the configuration refresh function of the client.

With Spring Cloud Bus, we only need to create a simple request and add the @ ResfreshScope annotation to dynamically modify the configuration. I draw a diagram below for you to understand.

After reading this, the article "what are the basic knowledge points of Spring Cloud" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report