1. display stand composition
The reason for the API Gateway is the emergence of micro services architecture, different micro services in general have different service address, while external clients may need to call multiple service interfaces to complete a business needs, so that if the client directly with each micro-communication service, will have the following questions:
- The client repeatedly requested different micro-service, increases the complexity of the client.
- Cross-domain request, at a certain scene is relatively complicated process.
- Certification complex, each service requires independent certification.
- Difficult to reconstruct, with the iteration of the project may need to be re-divided micro service. For example, a plurality of services may be combined into one or a plurality of split into service. If the client directly communicate with the micro-services, then the reconstruction will be difficult to implement.
- Some services may use a micro-protocol firewall / browser unfriendly, direct access there will be some difficulties.
A gateway is an intermediate layer interposed between the client and server side, all external requests will go through this layer API gateway. In other words, implementing aspects of the API more on business logic and security, performance, monitoring can be handed over to the API Gateway to do, so the gateway performance, high availability, security is essential.
Note : the Spring Micro Cloud services to build OAuth2.0 authentication and authorization services
Common Gateway What?
Nginx, Kong, ZUUL, Spring Cloud Gateway (Spring Cloud official), Linkerd etc.
Spring Cloud Zuul
Zuul is open source Netflix micro-services gateway components, it can and Eureka, Ribbon, Hystrix and other components used in conjunction. Zuul core is a series of filters (such as: dynamic routing). Spring Cloud Zuul on Zuul have been integrated, making it easier to use with Spring Cloud.
Zuul1
Zuul1 Servlet based framework to build, uses a multi-threaded and blocked, i.e. a thread processing a connection request, in this way inside a serious delay, the equipment failure in many cases causes increased survival and increased thread connection occurs .
Zuul2
The biggest difference Zuul2 and Zuul1 it runs on both asynchronous and non-blocking frame, one thread per CPU core, handles all requests and responses, the life cycle of requests and responses are handled through events and callbacks, reducing this way the number of threads, so the overhead is small. Also, because data is stored in the same CPU, the CPU can be reused level caching, latency, and storm retry the previously mentioned problems but also reduce the number of connections and the queue storage by the number of events the way a lot of (relatively speaking lightweight thread switch level lot, naturally consume less). This change will greatly enhance the performance.
performance
Can refer to: Correction posts: Zuul & Spring Cloud Gateway & Linkerd performance comparison , in simple terms, Zuul 1.x is based on blocking IO's API Gateway, another good Spring Cloud Gateway performance.
High Availability
General production environment need to be registered to multiple nodes Zuul Eureka Server, you can achieve high availability of Zuul. In fact, high availability and other services in this case do high availability (for example: Eurka Server Cluster) program is no different. When Zuul client registers to the Eureka Server, the client will automatically query Zuul Zuul Server list from Eureka Server, and then use the load balancer component (for example: Ribbon) request Zuul cluster. Otherwise F5 may be realized using hardware or Nginx.
safety
After the micro-services of Spring Cloud, generally can be used in conjunction with Spring Cloud Security OAuth2.0, Token generated using JWT to verify the bills, but Spring Cloud Security is not yet support OpenID Connect protocol. Zuul will register themselves as service governance at Eureka, but also access to information for all other instances of micro-services from Eureka service governance. By building an independent OAuth2 authentication and authorization services, micro-alone service spin-off, which authentication and micro-business and service their relationship is not much, so these functions completely independent existence as a separate service. After independence, not to each micro-service call (general business services, including network), but a unified API calls through a gateway, to do pre-filter for micro-services interface, other micro-distributed system service and safety check interception interface.
Create a gateway service Zuul
Maven
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
@SpringBootApplication //@EnableOAuth2Sso @EnableZuulProxy public class MicrosrvZuulGatewayApplication { public static void main(String[] args) { SpringApplication.run(MicrosrvZuulGatewayApplication.class, args); } }
application.yml
Spring: file application: name: microsrv Zuul-Gateway- Server: Port: 5555 Eureka: instance: preferIpAddress: to true Client: the serviceUrl: defaultzone: http://10.255.131.162:8000/eureka/,http://10.255.131.163: 8000 / Eureka /, HTTP: //10.255.131.164: 8000 / Eureka / Zuul: Host: Connect-timeout-of millis: 20000 socket-timeout-of millis: 20000 ignoredServices: '*' prefix: / # API to set up a common prefix routes: the auth-Service-: path: / the auth / ** sensitiveHeaders: the serviceId: idsrv-Server Order-Service-: sensitiveHeaders: path: / Order / ** serviceId: order-service add-proxy-headers: true
Because Eureka to use service discovery, the request URL format of the form / service-id / ** will be automatically forwarded to the registered at the Eureka Server service id is the "service-id" micro-service applications. The above example we define two routing rules, such as forwards "order-service" request to the appropriate service-id of the service registration, may be modified by zuul.prefix = / api to configure a global address prefix configuration. Default Eureka Server will be exposed to all registered micro service on top of it. You can use zuul.ignored-services property to prohibit such behavior, and only explicitly configured services will be exposed.
Zuul integrate authentication and authorization OAuth2.0
Zuul integration OAuth2.0 there are two ideas, one is authorized to operate a server using public key authentication using JwtToken unified bill, judges and other authority at the gateway; the other is to make the resources side processing, gateway only route forward.
Resource-side configuration
maven
<!-- oauth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.0.5.RELEASE</version> </dependency>
Spring Boot
@SpringBootApplication @EnableResourceServer public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
@RestController public class AccountController { @GetMapping("/principal") @PreAuthorize("hasAnyAuthority('user')") public Principal user(Principal principal) { return principal; } @GetMapping("/query") @PreAuthorize("hasAnyAuthority('all')") public String all () { return "具有 all 权限"; } }
application.yml
logging: level: org.springframework: DEBUG server: port: 5000 security: oauth2: resource: # prefer-token-info: true # user-info-uri: http://localhost:8080/api/v1/users/principal # token-info-uri: http://localhost:8080/oauth/check_token jwt: # key-uri: http://localhost:8080/oauth/token_key key-value: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm4irSNcR7CSSfXconxL4 g4M4j34wTWdTv93ocMn4VmdB7rCBU/BlxXtBUf/cgLIgQhQrAPszSZSmxiEXCOkG Pr4aQBQuPgmNIR95Dhbzw/ZN0BnecAt3ZfkkDBHv8kH3kR/jYGTdwrxKeDgXGljN sTRhbjuASxPG/Z6gU1yRPCsgc2r8NYnztWGcDWqaobqjG3/yzFmusoAboyV7asIp o4yk378LmonDNwxnOOTb2Peg5PeelwfOwJPbftK1VOOt18zA0cchw6dHUzq9NlB8 clps/VdBap9BxU3/0YoFXRIc18nyzrWo2BcY2KQqX//AJC3OAfrfDmo+BGK8E0mp 8wIDAQAB -----END PUBLIC KEY-----
Finally, you can enable on Zuul @ EnableOAuth2Sso annotation as a client OAuth2.0 of (non-essential), so that when users access to the gateway is not authorized, it will jump to the authorization server login authorization.
security: oauth2: client: access-token-uri:http://localhost:8080/oauth/token user-authorization-uri: http://localhost:8080/oauth/authorize client-id: client_test client-secret: secret_test resource: user-info-uri: http://localhost:8080/api/v1/users/principal prefer-token-info: false
The reason for the API Gateway is the emergence of micro services architecture, different micro services in general have different service address, while external clients may need to call multiple service interfaces to complete a business needs, so that if the client directly with each micro-communication service, will have the following questions:
- The client repeatedly requested different micro-service, increases the complexity of the client.
- Cross-domain request, at a certain scene is relatively complicated process.
- Certification complex, each service requires independent certification.
- Difficult to reconstruct, with the iteration of the project may need to be re-divided micro service. For example, a plurality of services may be combined into one or a plurality of split into service. If the client directly communicate with the micro-services, then the reconstruction will be difficult to implement.
- Some services may use a micro-protocol firewall / browser unfriendly, direct access there will be some difficulties.
A gateway is an intermediate layer interposed between the client and server side, all external requests will go through this layer API gateway. In other words, implementing aspects of the API more on business logic and security, performance, monitoring can be handed over to the API Gateway to do, so the gateway performance, high availability, security is essential.
Note : the Spring Micro Cloud services to build OAuth2.0 authentication and authorization services
Common Gateway What?
Nginx, Kong, ZUUL, Spring Cloud Gateway (Spring Cloud official), Linkerd etc.
Spring Cloud Zuul
Zuul is open source Netflix micro-services gateway components, it can and Eureka, Ribbon, Hystrix and other components used in conjunction. Zuul core is a series of filters (such as: dynamic routing). Spring Cloud Zuul on Zuul have been integrated, making it easier to use with Spring Cloud.
Zuul1
Zuul1 Servlet based framework to build, uses a multi-threaded and blocked, i.e. a thread processing a connection request, in this way inside a serious delay, the equipment failure in many cases causes increased survival and increased thread connection occurs .
Zuul2
The biggest difference Zuul2 and Zuul1 it runs on both asynchronous and non-blocking frame, one thread per CPU core, handles all requests and responses, the life cycle of requests and responses are handled through events and callbacks, reducing this way the number of threads, so the overhead is small. Also, because data is stored in the same CPU, the CPU can be reused level caching, latency, and storm retry the previously mentioned problems but also reduce the number of connections and the queue storage by the number of events the way a lot of (relatively speaking lightweight thread switch level lot, naturally consume less). This change will greatly enhance the performance.
performance
Can refer to: Correction posts: Zuul & Spring Cloud Gateway & Linkerd performance comparison , in simple terms, Zuul 1.x is based on blocking IO's API Gateway, another good Spring Cloud Gateway performance.
High Availability
General production environment need to be registered to multiple nodes Zuul Eureka Server, you can achieve high availability of Zuul. In fact, high availability and other services in this case do high availability (for example: Eurka Server Cluster) program is no different. When Zuul client registers to the Eureka Server, the client will automatically query Zuul Zuul Server list from Eureka Server, and then use the load balancer component (for example: Ribbon) request Zuul cluster. Otherwise F5 may be realized using hardware or Nginx.
safety
After the micro-services of Spring Cloud, generally can be used in conjunction with Spring Cloud Security OAuth2.0, Token generated using JWT to verify the bills, but Spring Cloud Security is not yet support OpenID Connect protocol. Zuul will register themselves as service governance at Eureka, but also access to information for all other instances of micro-services from Eureka service governance. By building an independent OAuth2 authentication and authorization services, micro-alone service spin-off, which authentication and micro-business and service their relationship is not much, so these functions completely independent existence as a separate service. After independence, not to each micro-service call (general business services, including network), but a unified API calls through a gateway, to do pre-filter for micro-services interface, other micro-distributed system service and safety check interception interface.
Create a gateway service Zuul
Maven
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
@SpringBootApplication //@EnableOAuth2Sso @EnableZuulProxy public class MicrosrvZuulGatewayApplication { public static void main(String[] args) { SpringApplication.run(MicrosrvZuulGatewayApplication.class, args); } }
application.yml
Spring: file application: name: microsrv Zuul-Gateway- Server: Port: 5555 Eureka: instance: preferIpAddress: to true Client: the serviceUrl: defaultzone: http://10.255.131.162:8000/eureka/,http://10.255.131.163: 8000 / Eureka /, HTTP: //10.255.131.164: 8000 / Eureka / Zuul: Host: Connect-timeout-of millis: 20000 socket-timeout-of millis: 20000 ignoredServices: '*' prefix: / # API to set up a common prefix routes: the auth-Service-: path: / the auth / ** sensitiveHeaders: the serviceId: idsrv-Server Order-Service-: path: / Order / ** sensitiveHeaders: serviceId: order-service add-proxy-headers: true
Because Eureka to use service discovery, the request URL format of the form / service-id / ** will be automatically forwarded to the registered at the Eureka Server service id is the "service-id" micro-service applications. The above example we define two routing rules, such as forwards "order-service" request to the appropriate service-id of the service registration, may be modified by zuul.prefix = / api to configure a global address prefix configuration. Default Eureka Server will be exposed to all registered micro service on top of it. You can use zuul.ignored-services property to prohibit such behavior, and only explicitly configured services will be exposed.
Zuul integrate authentication and authorization OAuth2.0
Zuul integration OAuth2.0 there are two ideas, one is authorized to operate a server using public key authentication using JwtToken unified bill, judges and other authority at the gateway; the other is to make the resources side processing, gateway only route forward.
Resource-side configuration
maven
<!-- oauth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.0.5.RELEASE</version> </dependency>
Spring Boot
@SpringBootApplication @EnableResourceServer public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
@RestController public class AccountController { @GetMapping("/principal") @PreAuthorize("hasAnyAuthority('user')") public Principal user(Principal principal) { return principal; } @GetMapping("/query") @PreAuthorize("hasAnyAuthority('all')") public String all () { return "具有 all 权限"; } }
application.yml
logging: level: org.springframework: DEBUG server: port: 5000 security: oauth2: resource: # prefer-token-info: true # user-info-uri: http://localhost:8080/api/v1/users/principal # token-info-uri: http://localhost:8080/oauth/check_token jwt: # key-uri: http://localhost:8080/oauth/token_key key-value: | -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm4irSNcR7CSSfXconxL4 g4M4j34wTWdTv93ocMn4VmdB7rCBU/BlxXtBUf/cgLIgQhQrAPszSZSmxiEXCOkG Pr4aQBQuPgmNIR95Dhbzw/ZN0BnecAt3ZfkkDBHv8kH3kR/jYGTdwrxKeDgXGljN sTRhbjuASxPG/Z6gU1yRPCsgc2r8NYnztWGcDWqaobqjG3/yzFmusoAboyV7asIp o4yk378LmonDNwxnOOTb2Peg5PeelwfOwJPbftK1VOOt18zA0cchw6dHUzq9NlB8 clps/VdBap9BxU3/0YoFXRIc18nyzrWo2BcY2KQqX//AJC3OAfrfDmo+BGK8E0mp 8wIDAQAB -----END PUBLIC KEY-----
Finally, you can enable on Zuul @ EnableOAuth2Sso annotation as a client OAuth2.0 of (non-essential), so that when users access to the gateway is not authorized, it will jump to the authorization server login authorization.
security: oauth2: client: access-token-uri:http://localhost:8080/oauth/token user-authorization-uri: http://localhost:8080/oauth/authorize client-id: client_test client-secret: secret_test resource: user-info-uri: http://localhost:8080/api/v1/users/principal prefer-token-info: false