In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
It is believed that many inexperienced people have no idea about how to use Zuul routing gateway in SpringCloud. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
First, the role of Zuul 1. Gateway function
The gateway can expose all api uniformly and protect other service api interfaces and information from being called directly by the outside world.
The gateway can do identity authentication and authority authentication, prevent illegal requests and operate API, and protect services.
The gateway can realize the monitoring function, real-time log output and record the request.
The gateway can realize traffic monitoring, which makes it easy to downgrade the service in the case of high traffic.
two。 Intelligent routing
Zuul can be combined with Ribbon and Eureka to achieve intelligent routing and load balancing.
Through a certain strategy, request traffic is distributed to multiple instances in the cluster state.
API can be separated from the internal interface to facilitate single test.
Second, the working principle of Zuul
Zuul is based on Servlet and controls requests through custom ZuulServlet. There are a series of filters in Zuul, which are also the key to the implementation of Zuul. During request initiation and response, these filters are used to achieve the function of Zuul. There are four specific ones:
PRE filter: executed before the request is routed to a specific service, purpose: security authentication (identity verification, parameter verification, ip blacklist and whitelist)
ROUTING filter: executed when the requested service is transferred to a specific microservice instance, purpose: to make network requests (HttpClient is used by default)
POST filter: executed after the request is routed to the microservice, purpose: statistics, return response
ERROR filter: executed when an error occurs in other filters, purpose: to ensure that the request can respond correctly
There are four methods in ZuulFilter, and a filter can be implemented by inheriting ZuulFilter and overriding the following four methods.
Public String filterType (); returns the type of the Filter, such as the four filters above.
Public int filterOrder (); returns the order in which the filter is executed.
Public boolean shouldFilter (); returns whether the filter needs to be executed.
Public Object run (); performs specific filtering logic.
ZuulServlet, the core Servlet of Zuul, is responsible for initializing the ZuulFilter and orchestrating these filters, as specified in the service () method.
Public void service (ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {try {this.init ((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse); RequestContext context = RequestContext.getCurrentContext (); context.setZuulEngineRan (); try {this.preRoute ();} catch (ZuulException var13) {this.error (var13) This.postRoute (); return;} try {this.route ();} catch (ZuulException var12) {this.error (var12); this.postRoute (); return } try {this.postRoute ();} catch (ZuulException var11) {this.error (var11);}} catch (Throwable var14) {this.error (new ZuulException (var14, 500, "UNHANDLED_EXCEPTION_" + var14.getClass (). GetName () } finally {RequestContext.getCurrentContext () .unset ();}
RequestContext is the role responsible for contextual cohesion in ZuulFilter. It is a ConcurrentHashMap and contains the objects needed by Request and Response, routeType, routeHost and other contexts.
III. Project practice (1) Project building
Parent project zuul-test/pom.xml
Com.calvin.zuulzuul-testpom1.0-SNAPSHOT eureka-server user-service zuul-service org.springframework.boot spring-boot-starter-parent 1.5.3.RELEASE UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-dependencies Dalston.SR4 pom import
Zuul-service/pom.xml
Zuul-test com.calvin.zuul 1.0-SNAPSHOT4.0.0zuul-service org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-eureka org.springframework.cloud spring-cloud-starter-zuul org.springframework.boot spring-boot-maven-plugin
Zuul-service/ZuulApplication.java
/ *
* Startup class *
* @ author Calvin * @ date 2019-10-25 * @ since 1.0 * / @ SpringBootApplication@EnableEurekaClient@EnableZuulProxypublic class ZuulServerApplication {public static void main (String [] args) {SpringApplication.run (ZuulServerApplication.class, args);}}
Zuul-service/application.yml
Spring: application: name: zuul-serviceserver: port: 8030eureka: client: service-url: defaultZone: http://localhost:8010/eureka/ instance: hostname: localhostzuul: routes: user-api: path: / user/** serviceId: user-service
User-service/pom.xml
Zuul-test com.calvin.zuul 1.0-SNAPSHOT4.0.0user-service org.springframework.cloud spring-cloud-starter-eureka org.springframework.cloud spring-cloud-starter-feign org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin
User-service/application.yml
Spring: application: name: user-serviceserver: port: 8020eureka: client: service-url: defaultZone: http://localhost:8010/eureka/ instance: hostname: localhost
User-service/UserApplication.java
/ *
* Startup class *
* @ author Calvin * @ date 2019-10-25 * @ since 1.0 * / @ SpringBootApplication@EnableEurekaClient@EnableFeignClientspublic class UserApplication {public static void main (String [] args) {SpringApplication.run (UserApplication.class, args);}}
User-service/controller/UserController.java
/ *
* * @ author Calvin * @ date 2019-10-25 * @ since * / @ RestControllerpublic class UserController {/ * simply build a User * / @ GetMapping ("/ userDetail/ {userId}") public SysUser getUserDetail (@ PathVariable ("userId") String userId) {SysUser sysUser = new SysUser (); sysUser.setId (userId); sysUser.setAge (20); sysUser.setPassword (MD5Utils.digestAsHex ("123456")) SysUser.setUsername ("Calvin"); / / the picture is from Baidu sysUser.setHeadImg ("https://b-ssl.duitang.com/uploads/item/201510/17/20151017181645_c5hWE.thumb.700_0.jpeg"); return sysUser;}} (2) Intelligent routing).
Start eureka-server, user-server, zuul-server in turn
Browser calls http://localhost:8030/user/userDetail/1
You can see from the call result that we called the method of user-service from zuul-service, and the call was successful. Thus proving that the routing configuration is available
To configure the version number, we only need to add the configuration to our zuul-service/application.yml: zuul.prefix=v1
(3) Fault fuse
If you need to implement a service circuit breaker in Zuul, you only need to implement the ZuulFallbackProvider interface, override two of these methods, return the route we need to circuit breaker through the getRoute () method, and rewrite the logic executed during the circuit breaker through the fallbackResponse () method.
As follows, we implement the first user-service fuse
/ *
* user-service fuse *
* * @ author Calvin * @ date 2019-10-27 * @ since * / @ Componentpublic class UserServiceCallback implements ZuulFallbackProvider {@ Override public String getRoute () {return "user-service";} @ Override public ClientHttpResponse fallbackResponse () {return new CommonClientResponse ();}}
Affixing the code of CommonClientResponse is the encapsulation of the ClientHttpResponse interface.
/ *
Encapsulated generic return class
* * @ author Calvin * @ date 2019-10-27 * @ since * / public class CommonClientResponse implements ClientHttpResponse {@ Override public HttpStatus getStatusCode () throws IOException {return HttpStatus.OK;} @ Override public int getRawStatusCode () throws IOException {return 0;} @ Override public String getStatusText () throws IOException {return "success" } @ Override public void close () {} @ Override public InputStream getBody () throws IOException {return new ByteArrayInputStream ("hello, this is zuul fallback" .getBytes ());} @ Override public HttpHeaders getHeaders () {HttpHeaders headers = new HttpHeaders (); headers.setContentType (MediaType.APPLICATION_JSON); return headers;}}
Next, to do a test, we stop the user-service service and then access http://localhost:8030/user/userDetail/1
The result is, of course, what is returned in the fuse we defined!
If you need to use the same fuse for other services, simply return the wildcard return "*" in the getRoute () method and
Gateway testing
ZuulFilter is the key to Zuul's implementation of filtering and gateways, and this class has four enumerated values that represent the filter types in Zuul. If you need to implement filtering, you only need to inherit ZuulFilter and specify its filter type, and the enumeration value is:
/ * @ link ZuulFilter#filterType ()} error type. * / String ERROR_TYPE = "error"; / * {@ link ZuulFilter#filterType ()} post type. * / String POST_TYPE = "post"; / * {@ link ZuulFilter#filterType ()} pre type. * / String PRE_TYPE = "pre"; / * {@ link ZuulFilter#filterType ()} route type. * / String ROUTE_TYPE = "route"
Simply implement a filter
/ *
Header filter
* * @ author Calvin * @ date 2019-10-27 * @ since * / @ Componentpublic class TokenFilter extends ZuulFilter {private static final Logger logger = LoggerFactory.getLogger (TokenFilter.class); @ Override public String filterType () {return PRE_TYPE;} @ Override public int filterOrder () {return 0;} @ Override public boolean shouldFilter () {return true } @ Override public Object run () {RequestContext requestContext = RequestContext.getCurrentContext (); HttpServletRequest request = requestContext.getRequest (); logger.info ("request_url: {}, request_headers: {}", request.getRequestURI (), JSON.toJSON (request.getHeaderNames ()) .toString ()); return null;}}
Restart zuul-service and call the service console to output the following:
2019-11-12 22 com.calvin.zuul.filter.TokenFilter: request_url: / user/userDetail/1, request_headers: ["host", "connection", "cache-control", "upgrade-insecure-requests", "user-agent", "sec-fetch-user", "accept", "sec-fetch-site", "sec-fetch-mode", "accept-encoding", "accept-language", "cookie"]
If you need to intercept requests, or set whitelist, and set your own statusCode in RequestContext, you can do so.
RequestContext.setSendZuulResponse (false); requestContext.setResponseStatusCode (401); ctx.getResponse (). GetWriter (). Write ("there is no token found,please relogin!") After reading the above, have you mastered how to use the Zuul routing gateway in SpringCloud? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
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.