In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "what are the three key knowledge points of spring-cloud-kubernetes". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Where does the implementation class instance of the DiscoveryClient interface come from?
Let's first review the contents of DiscoveryController.java in the previous chapter:
} / * returns the result of the remote call * @ return * / @ RequestMapping ("/ getservicedetail") public String getUri (@ RequestParam (value = "servicename", defaultValue = "") String servicename) {return "Service [" + servicename + "]'s instance list:" + JSON.toJSONString (discoveryClient.getInstances (servicename)) } / * return all discovered services * @ return * / @ RequestMapping ("/ services") public String services () {return this.discoveryClient.getServices () .toString () + "," + new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (new Date ());}}
In the above code, we don't write the code to create an instance of DiscoveryClient. Where does discoveryClient come from?
It all starts with the pom.xml of the project where DiscoveryController.java works.
In pom.xml, there is a dependency configuration for the spring-cloud-kubernetes framework:
Org.springframework.cloud spring-cloud-kubernetes-discovery 1.0.1.RELEASE
Open the source code of spring-cloud-kubernetes-discovery at https://github.com/spring-cloud/spring-cloud-kubernetes/tree/master/spring-cloud-kubernetes-discovery, and found the file spring.factories in this project:
When the spring container starts, it will look for all the spring.factories files under classpath (including those in the jar file), and all the classes configured in spring.factories will be instantiated. We use this technology in developing XXX-starter.jar, which is often used in developing springboot. The effect is that once we rely on a certain starter.jar, many functions are automatically executed at spring initialization (for example, mysql's starter, which connects to the database when starting)
There are two classes in the spring.factories file: KubernetesDiscoveryClientAutoConfiguration and KubernetesDiscoveryClientConfigClientBootstrapConfiguration are both instantiated
Let's first look at KubernetesDiscoveryClientConfigClientBootstrapConfiguration, which is a simple source code. KubernetesAutoConfiguration and KubernetesDiscoveryClientAutoConfiguration classes are instantiated:
/ * Bootstrap config for Kubernetes discovery config client. * * @ author Zhanwei Wang * / @ Configuration@ConditionalOnProperty ("spring.cloud.config.discovery.enabled") @ Import ({KubernetesAutoConfiguration.class, KubernetesDiscoveryClientAutoConfiguration.class}) public class KubernetesDiscoveryClientConfigClientBootstrapConfiguration {}
In the source code of KubernetesAutoConfiguration, an important class is instantiated: DefaultKubernetesClient, as follows:
@ Bean@ConditionalOnMissingBeanpublic KubernetesClient kubernetesClient (Config config) {return new DefaultKubernetesClient (config);}
Let's take a look at the KubernetesDiscoveryClientAutoConfiguration source code and pay attention to the kubernetesDiscoveryClient method, which instantiates the DiscoveryClient interface implementation required by DiscoveryController, and also focuses on the value of the KubernetesClient parameter, which is the DefaultKubernetesClient object mentioned above:
Bean@ConditionalOnMissingBean@ConditionalOnProperty (name = "spring.cloud.kubernetes.discovery.enabled", matchIfMissing = true) public KubernetesDiscoveryClient kubernetesDiscoveryClient (KubernetesClient client, KubernetesDiscoveryProperties properties, KubernetesClientServicesFunction kubernetesClientServicesFunction, DefaultIsServicePortSecureResolver isServicePortSecureResolver) {return new KubernetesDiscoveryClient (client, properties, kubernetesClientServicesFunction, isServicePortSecureResolver);}
Another important point is to use the following: KubernetesDiscoveryClient has a member variable that is KubernetesClient, and its value is a DefaultKubernetesClient instance
Next, let's look at the second question.
How can java applications get the service information of their kubernetes?
Take a look at how DiscoveryController obtains the service information of its kubernetes:
@ RequestMapping ("/ services") public String services () {return this.discoveryClient.getServices () .toString () + "," + new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss") .format (new Date ());}
As shown above, the discoveryClient.getServices () method returns the service information of all kubernetes; 2. The corresponding class of discoveryClient is the KubernetesDiscoveryClient.java of the spring-cloud-kubernetes project, see the method:
Public List getServices (Predicate filter) {return this.kubernetesClientServicesFunction.apply (this.client) .list () .getItems () .stream () .filter (filter) .map (s-> s.getMetadata () .getName ()) .duration (Collectors.toList ());}
The key to this code is this.kubernetesClientServicesFunction.apply (this.client). List (), first look at the initialization process of the KubernetesClientServicesFunction instance, in the KubernetesDiscoveryClientAutoConfiguration class:
@ Beanpublic KubernetesClientServicesFunction servicesFunction (KubernetesDiscoveryProperties properties) {if (properties.getServiceLabels (). IsEmpty ()) {return KubernetesClient::services;} return (client)-> client.services () .withLabels (properties.getServiceLabels ());}
KubernetesClientServicesFunction is a lambda expression that returns the result of KubernetesClient.services () when used in KubernetesClient. If tag filtering is specified, it is filtered with the specified tag (that is, the effect of the tag selector in kubernetes).
Therefore, the data source is actually the above this.client, which calls the return result of its services method; 3. What is the this.client in the KubernetesDiscoveryClient.getServices method? As mentioned when analyzing the previous problem, it is an instance of the DefaultKubernetesClient class, so at this point you need to look at the DefaultKubernetesClient.services method and find that client is an instance of ServiceOperationsImpl:
Override public MixedOperation services () {return new ServiceOperationsImpl (httpClient, getConfiguration (), getNamespace ());}
Moving on to ServiceOperationsImpl.java, we are concerned with its list method, which is found in the parent class BaseOperation:
Public L list () throws KubernetesClientException {try {HttpUrl.Builder requestUrlBuilder = HttpUrl.get (getNamespacedUrl ()). NewBuilder (); String labelQueryParam = getLabelQueryParam (); if (Utils.isNotNullOrEmpty (labelQueryParam)) {requestUrlBuilder.addQueryParameter ("labelSelector", labelQueryParam);} String fieldQueryString = getFieldQueryParam (); if (Utils.isNotNullOrEmpty (fieldQueryString)) {requestUrlBuilder.addQueryParameter ("fieldSelector", fieldQueryString) } Request.Builder requestBuilder = new Request.Builder (). Get (). Url (requestUrlBuilder.build ()); L answer = handleResponse (requestBuilder, listType); updateApiVersion (answer); return answer;} catch (InterruptedException | ExecutionException | IOException e) {throw KubernetesClientException.launderThrowable (forOperationType ("list"), e);}}
Expand the handleResponse method in the above code, and you can see that there is a http request inside. As for the address of the request, you can expand the getNamespacedUrl () method. The getRootUrl method called in it is as follows:
Public URL getRootUrl () {try {if (apiGroup! = null) {return new URL (URLUtils.join (config.getMasterUrl (). ToString (), "apis", apiGroup, apiVersion));} return new URL (URLUtils.join (config.getMasterUrl (). ToString (), "api", apiVersion));} catch (MalformedURLException e) {throw KubernetesClientException.launderThrowable (e);}}
You can see that the final address should be a string like xxxxxx/api/v1 or xxxxxx/apis/xx/v1.
What does such a string mean? This is the standard URL format used to access kubernetes's API Server. For more information about the API Server service, please refer to the official document at https://kubernetes.io/docs/reference/using-api/api-concepts/
As shown in the following figure, using the source code of the OperationSupport class and the URL screenshot of the official document to make a comparison, you can see at a glance: 5. There is only one small question left. In the figure above, what is the value of the member variable resourceT of the OperationSupport class? In the official document example, it is "pods". How much should it be when getting service? Following the source code, we find the construction method of the class. As shown below, the fifth parameter is resourceT, which is directly written as "services":
Public ServiceOperationsImpl (OkHttpClient client, Config config, String apiVersion, String namespace, String name, Boolean cascading, Service item, String resourceVersion, Boolean reloadingFromServer, long gracePeriodSeconds, Map labels, Map labelsNot, Map labelsIn, Map labelsNotIn, Map fields) {super (client, config, null, apiVersion, "services", namespace, name, cascading, item, resourceVersion, reloadingFromServer, gracePeriodSeconds, labels, labelsNot, labelsIn, labelsNotIn, fields);}
At this point, the second question, "where does the kubernetes service data used in controller come from?" is clear: finally, the newCall method of okhttp is called to initiate a http request to kubernetes's API Server to get the data list of service resources.
Next, it's time for the last question.
What did API Server do after receiving the request?
This article only gives some brief instructions on how API Server responds to various http requests. For more information, please refer to the official documentation at https://kubernetes.io/docs/reference/command-line-tools-reference/kube-apiserver/.
As shown in the figure below, in the kubernetes environment, the data of resources such as pod and service are stored in etcd. Any service that wants to add, delete, modify and query the data of etcd can only be completed by initiating a RestFul request to API Server. Our DiscoveryController class also sends a request to API Server to obtain all service, and API Server obtains the data of service from etcd and returns it to DiscoveryController:
This is the end of the content of "what are the three key knowledge points of spring-cloud-kubernetes". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.