Why use a service registry?
- In microservices, the first problem we need to face is how to find services (software is a service),
- The second is how to communicate between different services?
- How to manage each service in the application better and more conveniently, and how to establish the link between various services, so that the registration center was born (for example, Taobao sellers provide services and buyers invoke services).
Common registries on the market (expansion)
Zookeeper (Yahoo Apache)
Eureka(Netfix)
Nacos(Alibaba)
Consul(Google)
What are their characteristics and how do we select them? We mainly consider community activity, stability, function and performance In this microservice study, we chose Nacos, which well supports Alibaba's double 11 activities. It can not only be used as a registration center, but also as a configuration center. It has good stability and performance
Introduction to Nacos registry
Nacos (dynamic naming and configuration service) is a platform applied to service registration, discovery and configuration management. It was incubated in Alibaba and grew up in the peak test of the double 11 in the past decade, precipitating the core competitiveness of simplicity, ease of use, stability and reliability and excellent performance. Its official website address is as follows:
https://nacos.io/zh-cn/docs/quick-start.html
Nacos itself is developed based on Spring boot MVC
Nacos provides the features of service registration, discovery and configuration
Nacos has high activity, stability, strong performance and low learning cost
The official website of Nacos is: Nacos io
Nacos in github source code: github com/alibaba/nacos
Under windows environment, Nacos can be used after decompression (JDK and database dependency are required)
Nacos Download
https://github.com/alibaba/nacos/releases
Nacos start
Linux/Unix/Mac startup command (standalone stands for stand-alone mode, non cluster mode):
./startup.sh -m standalone
Windows startup command (standalone stands for stand-alone mode, non cluster mode):
startup.cmd -m standalone
explain:
1) When executing the execution command, either configure the environment variable or execute it directly in the nacos/bin directory
2) When Nacos starts, Java needs to be configured in the local environment variable_ Home (corresponding to the jdk installation directory),
Accessing Nacos services
Open the browser and enter http://localhost:8848/nacos address
Default account password: nacos/nacos
Introduction to service registration and invocation (key points)
Create two project modules: service provider and service consumer. Both of them should be registered in the NacosServer (the server is essentially a web service, and the port is 8848 by default). Then the service provider can provide remote calling services for service consumers (for example, payment service is the service provider and order service is the service consumer), as shown in the figure:
Nacos version
For the version selection of Nacos, please refer to the following website (it involves a compatibility problem, and its version cannot be specified arbitrarily):
https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E
Creating a java microservice project
Configuration of root pom file (this pom is the root node and no code is required)
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <modules> <module>sca-provider</module> <module>sca-consumer</module> </modules> <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.3.2.RELEASE</version> </parent> <groupId>com.cy.jt</groupId> <artifactId>05-jt-sca</artifactId> <version>1.0-SNAPSHOT</version> <properties> <spring.cloud>Hoxton.SR8</spring.cloud> <spring.cloud.alibaba>2.2.5.RELEASE</spring.cloud.alibaba> </properties> <!--Dependent version management--> <dependencyManagement> <dependencies> <!--spring cloud rely on,This dependency requires springboot Support of,Defined in this dependency spring cloud Microservice specification--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring.cloud}</version> <!--import Indicates that the subproject under this project can directly reference the version in this dependency--> <scope>import</scope> <!--When scope by import Time,The type here must be pom type--> <type>pom</type> </dependency> <!--spring cloud alibaba rely on,This dependency depends on spring cloud,The current dependency is implemented based on the microservice specification--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring.cloud.alibaba}</version> <scope>import</scope> <type>pom</type> </dependency> </dependencies> </dependencyManagement> </project>
explain:
- Since Maven only allows to inherit one < parent >, in order to make the subproject inherit more POMS, use < dependency Management > to add multiple dependent POMs
- The parent project will only be responsible for deleting. src resources after the parent project is initialized
Create provider services and consumer projects
Subproject configuration
server: port: 8090 spring: application: name: sca-consumer # Represents the service name of the project, which will be presented in the nacos registry later cloud: nacos: discovery: server-addr: localhost:8848 # Where to find (register) the service and link to the address of the service registry feign: # When the feign mode service call interface is enabled, if an exception occurs, the default processing mechanism will be executed hystrix: enabled: true # The default value of the new version is false: the default processing mechanism will not be executed even if an exception occurs
Note: do not use underscores ("") for service names, A bar ("-") should be used, which is the rule.
Server addr: if not written, the default is localhost:8848
When the above points are configured, start the Nacos service and start the project to register the service (project) with Nacos
Nacos summary
1. Why register the service with nacos?
In order to better find these services and get unified management
2. How do service providers renew their contracts with the Nacos registry in Nacos?
When a project is started, a web request will be sent to Nacos to send a heartbeat packet to register with Nacos
The program will send a heartbeat to nacos every 5s by default
3. For Nacos service, how does it determine the status of service instances?
If the instance is checked for more than 15s, the heartbeat has not been sent. The instance health status will be changed to false
If no heartbeat is received in 30s, nacos will remove the item.
To rewrite and add, restart the project and register the service
4. How to find the service startup registration configuration class during service startup?
By relying on the built-in NacosNamingService class
5. How does the service consumer invoke the services of the service provider?
Through RestTemplate object
6. What is the core data of the registry?
The name of the service and its corresponding network address
7. Why does the registry use a read-write lock to access the core data?
Underlying security and performance (see AbstractHandlerMethodMapping class)
8. How does Nacos ensure high availability?
Retry after disconnection + local cache + cluster
Design and implementation of Nacos service load balancing
explain:
A service instance can process requests is limited. If the concurrent access of a service instance is relatively large, we will start multiple service instances and let these service instances process concurrent requests with certain policy balance (polling, weight, random, hash, etc.). The following is the load balancing example implemented by Nacos
1. Remotely call the service of the provider based on the RestTemplate object
Instantiate the RestTemplate object and add the object to the IOC(Bean) container
//Remote call microservice object: it is used to access remote services based on this object, which is built in Spring MVC @Bean public RestTemplate restTemplate() { return new RestTemplate(); }
Send an hppt request through getForObject of RestTemplate object
@Autowired private RestTemplate restTemplate; @GetMapping("/consumer/doRestEcho1") public String doRestEcho01() { String url = "http://localhost:8081/provider/echo/"; //A remote procedure call initiates a request (RPC) to the provider return restTemplate.getForObject(url, String.class); }
explain
Although this method can call the interface remotely, it does not have the characteristics of load balancing
It does not need to rely on nacos to make service calls directly through fixed ip and port
This method is not suitable for multi service instance invocation
2. Remote service call based on RestTemplate
@Autowired //Load balancer client: Based on this object, you can get a service instance from the registry private LoadBalancerClient loadBalancerClient; @GetMapping("/consumer/doRestEcho2") public String doRestEcho02() { //Based on the service name passed by the loadBalancerClient object, search the service instance (there may be multiple) according to the service name from the nacos registry ServiceInstance choose = loadBalancerClient.choose("sca-provider"); //The queried services are selected according to the default polling method, and the IP + port services (the algorithm selects the service instance) String host = choose.getHost();//ip address (the ip address here is not fixed) int port = choose.getPort();//Get the port number (the port number here is not fixed) String url = "http://" + host + ":" + port + "/provider/echo/"; return restTemplate.getForObject(url, String.class); //Remote call service }
LoadBalancerClient Object Description:
- This object will be automatically injected into the container with IOC when the project is started without configuration
- It returns a ServiceInstance object, which contains all the services queried according to demand. At this time, the service instance will be selected locally according to a certain algorithm
- By default, IP + port services are selected by polling
explain
This method has a large amount of code. Is there an access method to achieve load balancing through a small amount of code?
3. Optimize the code by integrating the RestTemplate object with @ LoadBalanced
Integrate the restTemplate remote call object with the load balancing client
The RestTemplate object will automatically add the LoadBalanced load balancing function
@Bean @LoadBalanced public RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); }
// This object now has the function of load balancing client + remote procedure call object @Autowired private RestTemplate loadBalancedRestTemplate; @GetMapping("/consumer/doRestEcho3") public String doRestEcho03() { // Http: / service name registered on Nacos / interface of the service // When the loadBalancedRestTemplate is parsed, the service name will be changed to IP + port by default String url = "http://sca_provider/provider/echo"; return loadBalancedRestTemplate.getForObject(url, String.class); }
@What is the role of LoadBalanced?
It describes the RestTemplate object, which is used to tell the Spring framework that when using RestTempalte for service calls,
This calling process will be intercepted by an interceptor, and then the load balancing strategy will be started inside the interceptor
explain
Although this method simplifies the code, it is not particularly efficient for the following reasons:
- Although it makes remote service calls based on RestTemplate with load balancing feature,
- However, it will be slightly less efficient than mode 2, because the bottom layer will intercept requests,
- After interception, obtain the service instance based on loadBalancerClient for calling
Summary description
1. How does Nacos achieve load balancing?
Here, multiple instances provide services concurrently by load balancing,
It is implemented by Nacos integrating Ribbon. The default polling policy is load balancing
Ribbon and RestTemplate can easily access services.
2. What is Ribbon?
Ribbon is one of the core components of Spring Cloud. The most important function it provides is load balancing on the client
(the client can use certain algorithms, such as polling access to access the server instance information)
This function allows us to easily automatically convert service-oriented REST template requests into client-side load balancing service calls
3. What is ribbon load balancing strategy
Based on Ribbon load balancing, Netflix provides seven load balancing strategies by default. For spring cloud Alibaba solution, it also provides NacosRule strategy. The default load balancing strategy is rotation training strategy!
A total of 8 types can be analyzed by viewing the implementation classes of the IRule interface
When the load balancing policy provided by the system cannot meet our needs, we can also define our own policy based on IRule interface
4. How is the bottom layer responsible for balancing in Nacos realized?
Through the Ribbon implementation, some load balancing algorithms are defined in the Ribbon, and then an instance is obtained from the service instance based on these algorithms to provide services for the consumption method
5. What is ribbon
The load balancing client provided by Netflix is generally applied to the service consumption method. Later, it was integrated by Spring due to open source
6. What problems can ribbon solve?
Service invocation is based on load balancing policy, and all policies will implement IRule interface
7. Can we define our own load balancing strategy?
Yes, the policy can be defined based on IRule interface or implemented with reference to NacosRule
Call and practice of remote service based on Feign
Background analysis:
When the service consumer requests the service of the service provider based on rest, a direct way is to splice the url, splice the parameters, and then implement the service call. However, this splicing is required for each service call. The amount of coding is complex and difficult to maintain. At this time, Feign was born
What is Feign
Feign is a declarative Web service client. The bottom layer encapsulates the application of Rest technology. Feign can simplify the call and implementation of remote service provider methods by service consumers. As shown in the figure:
Feign was first maintained by Netflix. Later, Netflix no longer maintained feign. Finally, feign was maintained by the community and renamed OpenFeign.
Why Feign
Clear structure, strong code logic and repeatable call
Implementation of Feign
1. Rely on jar package (spring cloud team developed starter based on OpenFeign)
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
2. The service layer defines Feign's remote service invocation interface
@FeignClient(name = "sca-provider",contextId = "remoteProviderService", fallbackFactory = RemoteProviderFallbackFactory.class) public interface RemoteProviderService { //The parameter of GetMapping must be the same as the address of the remote service (the request method is the same) @GetMapping("/provider/echo/{msg}") String echoMsg(@PathVariable("msg") String msg); }
Interface Description:
This interface does not require us to write our own implementation class. The bottom layer will help us create (proxy object) when the service is started and make remote service calls inside the implementation class
Parameter Description:
Name: defines the server under which Feign accesses the service name in nacos (value: the service name in nacos)
contextId:
For a context id, the current interface name is generally written to distinguish service calls; Because a service provider will provide many resource calls in the future, if the service consumption method writes many service call interfaces based on the same service provider, the service startup will fail if the contextId is not specified
fallbackFactory:
Used to specify the default result that should be returned to the client when the service terminates or reports an exception. This object will be called when an exception occurs in the remote call,
If contestId is not specified, Feign will register according to name when registering the service to the Bean,
Next is the specific implementation:
3. The exception occurred when configuring Feign interface call. The class method called by default
@Service //RemoteProviderService: indicates that this class is only responsible for the processing mechanism after the exception occurred in RemoteProviderService public class RemoteProviderFallbackFactory implements FallbackFactory<RemoteProviderService> { //This method will execute the specified Feign interface service when an exception occurs when the call fails //throwable is used to receive exceptions @Override public RemoteProviderService create(Throwable throwable) { return (msg) -> { System.out.println(throwable.getLocalizedMessage()); return throwable.getMessage(); }; } }
Note: when this class implements the FallbackFactory interface, pay attention to writing generics
Generic classes are Feign interface classes that need to be caught and may have exceptions
4. Enable Feign's exception handling mechanism
Configuration file settings in spring
feign: hystrix: enabled: true # Enable Feign's exception handling mechanism
Its default value is false, which means:
When calling the service interface in feign mode, if an exception occurs, the default execution is no processing
5. The main class or configuration class declares that Spring cloud starts feign service invocation
@EnableFeignClients @SpringBootApplication public class ScaConsumerApplication { public static void main(String[] args) { SpringApplication.run(ScaConsumerApplication.class, args); } }
@EnableFeignClients: can describe the reconfiguration class. Because the main class is also a configuration class by default, it can also be used in the main class
Function: when Spring cloud starts, feign will be used to call the service of the provider in nacos
Implementation: automatically scan the interface described by @ FeignClient annotation when the service is started, and create a proxy object based on the interface. The Feign proxy object will help us initiate remote service calls
Feign application call process analysis (underlying logic)
- Tell springcloud through the @ EnableFeignCleints annotation to start the Feign Starter component.
- Feign Starter registers the global configuration during project startup, scans the interface described by @ FeignClient annotation under the package, then creates the interface implementation class (JDK proxy class) at the bottom of the system, constructs the class object, and then submits it to spring management (registers the IOC container).
- When the interface is called, it is intercepted by the dynamic proxy class logic. The @ FeignClient Request information is generated into a Request object through the encoder, and remote procedure calls are made based on this object.
- The request object performs load balancing through the Ribbon and selects a healthy Server instance.
- The Client carries the Request and calls the remote service to return the Request response.
- The decoder generates a Response to return to the client, and parses the information flow into interface return data.
Feign's summary
1. Why use feign?
Based on Feign, the service invocation can be implemented more friendly and the invocation of service provider methods by service consumers can be simplified
2. What is the function of @ feignclient annotation?
Tell Feign Starter to create an implementation class proxy class for the interface described in this annotation when the project starts
3. How is the underlying load balancing implemented for feign mode calls?
Ribbon
4. What is the function of @ enablefeigncleints annotation?
Describes configuration classes, such as startup classes
Nacos summary
1. What is a registry?
A web service used to record service information
2. The core object of the registry?
Service provider, service consumer, Registry, etc
3. What are the commonly used registration centers in the market?
Google-Consul,Alibaba-Nacos,...
4. Construction process of the project under the micro service architecture
Aggregate engineering is required