1. What are microservices
Microservices were first proposed by Martin Fowler and James Lewis in 2014. Microservices architecture style is a way to develop a single application using a set of small services. Each service runs in its own process and uses a lightweight mechanism to communicate, usually HTTP API. These services are built on business capabilities and can be deployed independently through automated deployment mechanisms, implemented using different programming languages, and different data storage technologies, with minimal centralized management.
2. Why microservices
In the traditional IT industry software is mostly a pile of various independent systems, the problems of these systems can be summed up as poor scalability, low reliability and high maintenance costs. SOA servitization was introduced later, but because of the early use of the Bus pattern in SOA, the bus pattern was strongly tied to a technology stack, such as J2EE. As a result, the legacy systems of many enterprises are difficult to connect, the switching time is too long, the cost is too high, and the convergence of the stability of the new system takes some time.
3. Differences between microservices and individual architectures
(1) All modules of a single architecture are coupled together, resulting in a large amount of code and difficulty in maintenance.
Microservices each module is equivalent to a separate project, the amount of code is significantly reduced, problems are relatively easy to solve.Copy the code
(2) Single architecture all modules share a database, and the storage mode is relatively single.
Each module of microservice can use different storage methods (for example, some use Redis, some use mysql, etc.), and the database is also a single module corresponding to its own database.Copy the code
(3) Single architecture All modules are developed using the same technology.
Each module of microservices can use different development technology, and the development mode is more flexible.Copy the code
4. The nature of microservices
(1) service, the key is not just the service itself, but the system to provide a basic architecture, this architecture makes the service can be independent of the deployment, operation, upgrading, not only that, the system architecture also let micro service and micro service between “loose coupling” in the structure, and on the function of a unified whole. This so-called “unified whole” shows a unified style of interface, unified permission management, unified security policy, unified online process, unified log and audit methods, unified scheduling, unified access and so on. (2) The purpose of microservices is to effectively split applications and achieve agile development and deployment. (3) Micro-service advocates the concept of inter-operate and not integrate between teams. Inter-operate is to define the boundaries and interfaces of the system, stack the whole within a team, and let the team be autonomous. The reason is that if the team is organized in this way and the communication cost is maintained within the system, each subsystem will be more cohesive, the dependence and coupling energy of each other will be weakened, and the communication cost across the system will be reduced.
5. Microservices development framework
At present, the most commonly used development frameworks for microservices are as follows:
Spring Cloud: projects. Spring. IO/Spring – clou…
Dubbo: http://dubbo.io
Dropwizard: www.dropwizard.io (Focus on the development of individual microservices)
Consul, etcd&etc. (module of microservice)
6. What is SpringCloud
Spring Cloud is a collection of frameworks. It leverages the development convenience of Spring Boot to simplify the development of distributed system infrastructure, such as service discovery, service registration, configuration center, message bus, load balancing, fuses, data monitoring, etc., all can be started and deployed with one click with Spring Boot development style. Spring did not repeat the wheel, it is only to the companies to the development of more mature, stand the test the actual service framework, encapsulation blocked again by SpringBoot style complex configuration and implementation principle, finally to developers to set aside a set of simple, easy deployment and maintenance of the distributed system development kit
7. Relationship between SpringBoot and SpringCloud
Spring Boot is a set of fast configuration scaffolding of Spring, you can quickly develop a single micro service based on Spring Boot, Spring Cloud is a development tool based on Spring Boot implementation; Spring Boot focuses on fast and easy integration of a single microservice individual, while Spring Cloud focuses on the global service governance framework. Spring Boot uses the concept of default being greater than configuration. Many integration solutions have already been selected for you. A large part of Spring Cloud is implemented based on Spring Boot and must be developed based on Spring Boot. You can develop projects using Spring Boot alone, but Spring Cloud can’t do without Spring Boot.
8. SpringCloud related basic service components
Service Discovery — Netflix Eureka (Nacos) Service Invocation — Netflix Feign Fuse — Netflix Hystrix Service GateWay — Spring Cloud GateWay Distributed Configuration — Spring Cloud Spring Cloud Bus (Nacos)
8.1 Use of NACOS
Download nacos 8.1.1
- Download: github.com/alibaba/nac… Unzip to any directory
- Start the NacOS service
- Linux/Unix/Mac
Startup command (run in standalone mode, not in cluster mode) Startup command: sh startup.sh -m standalone
- Windows
Run the CMD startup. CMD command or double-click the startup. Visit: http://localhost:8848/nacos user name password: nacos/nacos
8.2 Service Registration
1. Add dependencies to the module
<! - the service registry - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>****<version> </dependency>Copy the code
2. Add the following configuration to the application.properties configuration file of the module
# configuration service name spring. Application. Name = # service - edu nacos service address spring. Cloud. Nacos. Discovery. The server - addr = 127.0.0.1:8848Copy the code
3. Add annotations to the module’s startup class
@EnableDiscoveryClient
Copy the code
4. Start the nacOS client in the browser
Start the registry starts registered microservices, which can be seen in the Nacos service list
8.3 Service Invocation (Feign)
1. Add dependencies to the module
<! - the service call - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code
2. Annotate the startup class on the calling side (figure below)
3. Create corresponding packages and interfaces in the calling module
- Create a client package
- The @FeignClient annotation is used to specify from which service the function is invoked, with the same name as the service being invoked.
- The @getMapping annotation is used to map the address of the microservice being invoked.
- The @pathVariable annotation must specify the parameter name, otherwise it will fail
- The @Component annotation prevents IDEA from reporting errors when CodClient is injected elsewhere
The interface content is as follows:
4. Inject the interface into the business layer and call it!
8.4 Fuse (Hystrix)
SpringCloud invokes the interface as follows:
(1) Interface Request Invocation When an interface modified by @FeignClient annotation is called, the Request is converted into Feign’s Request instance feign.Request within the framework, which is processed by Feign framework. Feign is a lightweight framework for invoking HTTP requests as Java interface annotations, encapsulating the HTTP invocation process.
(3) Hystrix: Circuit breaker processing mechanism The Feign call relationship will be intercepted by Hystrix proxy. For each Feign call request, Hystrix will wrap it into HystrixCommand and participate in Hystrix flow control and circuit breaker rules. If the request determines that a fusing is required, Hystrix directly fuses, throws an exception, or uses FallbackFactory to return the fusing Fallback result. If it passes, the invocation request is passed to the Ribbon component.
(4) Ribbon: Service Address Selection When a request is sent to the Ribbon, the Ribbon selects an appropriate service instance from the service list based on the quality of service it maintains, such as average response time, Load, and other specific rules. The machine instance information request is then passed to the HttpClient Client, which performs the real Http interface call;
(5) HttpClient: the Http client that performs the actual Http calls. The upper Ribbon delivers the request. If the server address is specified, the HttpClient will perform the actual Http requests
Feign is used in conjunction with Hystrix
- Import dependence
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <! - hystrix dependence, Mainly use @ HystrixCommand - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <! - the service registry - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <! - the service call - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code
- Enable fuse configuration in the configuration file
Feign.hystrix. enabled=true # Set hystrix timeout, The default 1000 ms hystrix.com mand. Default. Execution. The isolation. Thread. TimeoutInMilliseconds = 6000Copy the code
- Create an implementation class for the fuse in client (the package that contains the service invocation interface)
The code is as follows:
/** * A method of this class will be executed when a circuit breaker occurs when a remote call to the corresponding method fails! * orderClient: The service call class See this article - > 8.3.3 are included * / @ Component public class VodFileDegradeFeignClient implements OrderClient {@ Override public R IsBuyCourse (String courseId,String memberId) {return r.ror (). Message (" Delete video failed!" ); }}Copy the code
- Modify the annotations of the orderClient interface
- Just test it!
8.5 Service GateWay GateWay (can be regarded as a separate service module)
1. Gateway introduction
The reason for the emergence of API gateway is the emergence of micro-service architecture. Different micro-services generally have different network addresses, and external clients may need to call the interfaces of multiple services to complete a business requirement. If clients are allowed to directly communicate with each micro-service, the following problems will occur:
(1) The client will request different micro-services for many times, increasing the complexity of the client.
(2) There are cross-domain requests, which are relatively complicated to process in certain scenarios.
(3) Authentication is complicated, and each service needs independent authentication.
(4) It is difficult to reconstruct, and with the iteration of the project, microservices may need to be reclassified. For example, you might combine multiple services into one or split a service into multiple services. Refactoring can be difficult to implement if the client communicates directly with the microservice.
(5) Some microservices may use firewall/browser unfriendly protocols, so direct access will be difficult.
These issues can be addressed with API gateways. The API gateway is the middle layer between the client and server, where all external requests pass first. That is, apis are implemented with more business logic in mind, while security, performance, and monitoring can be left to THE API gateway to improve business flexibility without compromising security
2. GateWay GateWay
- Create a separate GateWay module
2. Import dependencies
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <! - the service registry - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <! --gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <! - the service call - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Copy the code
- Write the application.properties configuration file
Server.port =8010 server.port=8010 server.application. Name =service-getway Spring. Cloud. Nacos. Discovery. Server - addr = 127.0.0.1:8848 # use routing true service discovery can be found in the nacos other routing Spring. Cloud. Gateway. The discovery) locator) enabled = true # set routing id # * * * * * * * id can literally take, Generally the same as the service name * * * * * * * spring in cloud. The gateway. The routes [0]. Id = service - edu # set routing uri (must be in the service's name in the nacos) Spring. Cloud. Gateway. Routes [0]. Uri = lb: / / service - edu # set routing assertions, agent servicerId auth - service/auth/path # * * * * * * * * * * * * * * * * / edUservice/is the path in the @requestMapping annotation on controller, According to matching Path forward * * * * * * * * * * * * * spring in cloud. Gateway. The routes. [0] predicates = Path = / eduservice / * * # configuration service - edu service spring.cloud.gateway.routes[1].id=service-oss spring.cloud.gateway.routes[1].uri=lb://service-oss spring.cloud.gateway.routes[1].predicates= Path=/eduoss/** spring.cloud.gateway.routes[2].id=service-cms spring.cloud.gateway.routes[2].uri=lb://service-cms spring.cloud.gateway.routes[2].predicates= Path=/educms/** spring.cloud.gateway.routes[3].id=service-ucenter spring.cloud.gateway.routes[3].uri=lb://service-ucenter spring.cloud.gateway.routes[3].predicates= Path=/eduucenter/** spring.cloud.gateway.routes[4].id=service-statistics spring.cloud.gateway.routes[4].uri=lb://service-statistics spring.cloud.gateway.routes[4].predicates= Path=/edustatistics/** spring.cloud.gateway.routes[5].id=service-order spring.cloud.gateway.routes[5].uri=lb://service-order spring.cloud.gateway.routes[5].predicates= Path=/eduorder/** spring.cloud.gateway.routes[6].id=service-vod spring.cloud.gateway.routes[6].uri=lb://service-vod spring.cloud.gateway.routes[6].predicates= Path=/eduvod/** spring.cloud.gateway.routes[7].id=service-acl spring.cloud.gateway.routes[7].uri=lb://service-acl spring.cloud.gateway.routes[7].predicates= Path=/*/acl/** #spring.cloud.gateway.routes[7].id=service-oss #spring.cloud.gateway.routes[7].uri=lb://service-oss #spring.cloud.gateway.routes[7].predicates= Path=/eduoss/** #....................Copy the code
- Writing a startup class
@SpringBootApplication @EnableDiscoveryClient public class GetwayApplication { public static void main(String[] args) { SpringApplication.run(GetwayApplication.class,args); }}Copy the code
3. Configure the gateway
1. Resolve cross-domain problems
- Creating a Configuration Class
The code is as follows:
@configuration public class CorsConfig {@bean public CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); }}Copy the code
Conclusion: there are still a lot of others, but I do not know much about them at present. As a learning record, I will not continue to go further. I will learn more and then gradually improve it.
Recommend a micro service introduction: www.zhihu.com/question/65… Content reference: Silicon Valley Grain Institute