An API gateway is a server that is the only portal to the system. From an object-oriented design perspective, it is similar to the appearance pattern. The API gateway encapsulates the system's internal architecture and provides a custom API for each client. It may also have other responsibilities, such as authentication, monitoring, load balancing, caching, request fragmentation and management, and static response processing.
API gateways are used to provide API interfaces to external applications (PC clients, mobile terminals, external systems, etc.) as per usage scenarios. The previous chapter has realized the mutual invocation of the internal service of the system, the internal service is not open to the outside world, the external application wants to invoke the service, then the API gateway is needed to implement the route.
Spring Cloud's Integrated API gateways are: Netflix's Zuul and its own spring Cloud Gateway, which currently uses Zuul more and more data, Zuul as an API gateway.
1. Create an API Gateway Service
1.1 Adding Zuul dependencies
Create an empty MAVEN project Apigateway and add Zuul dependencies, because the API Gateway is also a service that needs to be registered to Eureka Server, so you also need to add Eureka client dependencies.
<Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-web</Artifactid></Dependency><Dependency> <groupId>Org.springframework.cloud</groupId> <Artifactid>Spring-cloud-starter-netflix-eureka-client</Artifactid></Dependency><Dependency> <groupId>Org.springframework.cloud</groupId> <Artifactid>Spring-cloud-starter-netflix-zuul</Artifactid></Dependency>
Adding @enablezuulproxy annotations on the startup class
Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;Importorg.springframework.cloud.netflix.zuul.enablezuulproxy;@ Springbootapplication@enableeurekaclient@enablezuulproxy Public classapigatewayapplication { Public Static voidMain (string[] args) {Springapplication.run (apigatewayapplication.class, args); }}
Configuration file set port and service center address
Server: 5551 #服务端口eureka: client: true #是否注册 true #启用客户端缓存 Serviceurl: defaultzone:http://peer1:8881/eureka/,http://peer2:8882/eureka/# Register to two service centres Spring: application: name:apigateway #服务名
Start Eureka Server, order service, User Service, API Gateway service, browser with Eureka Server page, and discover that the API Gateway service is registered successfully.
1.2 Setting the time-out period
Access User Services via API gateway, zuul Default routing rule: Http://zuul host address: Zuul Port/Service Name/service method address to invoke
Open Http://localhost:5551/userservice/user/getall in Browser
Error:
This application have no explicit mapping for/error, so is seeing this as a fallback.
Tue 17:49:01 CST 2018
There is an unexpected error (Type=gateway Timeout, status=504).
Com.netflix.zuul.exception.ZuulException:Hystrix readed Time Out
This error is expected to be Zuul the default time-out period is small, we configure the Zuul time-out period, because Zuul enabled the Ribbon load balancing, also need to set the ribbon time-out, note that the ribbon time-out is less than the Zuul time-out.
Zuul: Host: connect-timeout-millis:15000 #HTTP连接超时要比Hystrix的大 Socket- timeout-millis:60000 #socket超时ribbon: 10000 10000
If you have enabled Hystrix, you also need to set the Hystrix time-out period, note that the Hystrix timeout is less than the Zuul time-out.
hystrix: command: default: execution: timeout: true Isolation: thread: 10000 #设置超时时间 10 seconds
The service is then invoked through the gateway and the data is returned successfully.
If you need to do zuul filtering, interception, etc., you can refer to the official website document: Http://cloud.spring.io/spring-cloud-static/Finchley.SR1/single/spring-cloud.html#_ Router_and_filter_zuul
Create a new class that inherits Zuulfilter in the Gateway project, and then write the filtering logic in the class, such as parameter filtering
Public classQueryparamprefilterextendsZuulfilter {@Override Public intFilterorder () {returnPre_decoration_filter_order-1;//Run before Predecoration} @Override PublicString FilterType () {returnPre_type; } @Override Public BooleanShouldfilter () {RequestContext CTX=Requestcontext.getcurrentcontext (); return!ctx.containskey (Forward_to_key)//a filter has already forwarded&&!ctx.containskey (Service_id_key);//A filter has already determined serviceId} @Override PublicObject Run () {RequestContext CTX=Requestcontext.getcurrentcontext (); HttpServletRequest Request=ctx.getrequest (); if(Request.getparameter ("sample")! =NULL) { //put the serviceId in ' RequestContext 'Ctx.put (Service_id_key, Request.getparameter ("foo"))); } return NULL; }}
2. The client invokes the service through the API Gateway
2.1. NET Core Call Gateway Service
Create a new console program in VS and use HttpClient to invoke the service
classprogram{Static voidMain (string[] args) { stringUserserviceurl ="http://localhost:5551/userservice/user/";//invoking a service through a gateway address varClient =NewHttpClient {baseaddress =NewUri (Userserviceurl)}; Httpresponsemessage Response= client. Getasync ("GetAll"). Result; stringResponsestr =Response. Content.readasstringasync (). Result; Console.WriteLine (RESPONSESTR); Console.readkey (); }}
Starts the console and successfully returns the JSON data for the user information.
This completes the API gateway configuration.
With regard to security and authentication authorization,. NET core uses more IdentityServer4, because we now use the system has its own authorization authentication method (timestamp to do the time, user name + password or Apikey signature to do authentication), Temporarily without IdentityServer4.
Upgrading the MicroServices Architecture 5:API Gateway