Nine, Springcloud service Gateway Zuul (ii)

Source: Internet
Author: User

First, Route fuse

when our backend service is out of the ordinary, we do not want to throw the exception to the outermost layer and expect the service to automatically downgrade . Zuul provided us with such support. When a service has an exception, return to our preset information directly.

We do this by customizing the fallback method and assigning it to a route to implement the fuse processing of the route access problem. The main inheritance zuulfallbackprovideR interface to implement, zuulfallbackprovider default has two methods, one to indicate the fuse interception which service, a custom return content .

 public  interface   Zuulfallbackprovider { /**   * the R     Oute This fallback is used for. *   @return   The route the fallback would be used     For.   */ public      String Getroute ();      /**   * provides a fallback response.     *   @return   The fallback response.   */ public   Clienthttpresponse fallbackresponse ();}  

The implementation class, by implementing the Getroute method, tells Zuul that it is responsible for which route definition is fused. The Fallbackresponse method is to tell Zuul when a break occurs, it provides a return value to handle the request.

Spring then extended this class, enriched the return method and added exception information to the returned content, so the latest version suggests inheriting the class FallbackProvider directly.

Take the Spring-cloud-producer service as an example to customize its fusing back content.

@Component Public classProducerfallbackImplementsFallbackprovider {Private FinalLogger Logger = Loggerfactory.getlogger (fallbackprovider.class); //Specifies the service to be processed. @Override PublicString Getroute () {return"Spring-cloud-producer"; }     Publicclienthttpresponse Fallbackresponse () {return NewClienthttpresponse () {@Override PublicHttpstatus Getstatuscode ()throwsIOException {returnHttpstatus.ok; } @Override Public intGetrawstatuscode ()throwsIOException {return200; } @Override PublicString Getstatustext ()throwsIOException {return"OK"; } @Override Public voidclose () {} @Override PublicInputStream GetBody ()throwsIOException {return NewBytearrayinputstream ("The service is unavailable."). GetBytes ()); } @Override Publichttpheaders getheaders () {httpheaders headers=Newhttpheaders ();                Headers.setcontenttype (Mediatype.application_json); returnheaders;    }        }; } @Override Publicclienthttpresponse fallbackresponse (throwable cause) {if(Cause! =NULL&& cause.getcause ()! =NULL) {String reason=cause.getcause (). GetMessage (); Logger.info ("Excption {}", reason); }        returnFallbackresponse (); }}

When the service exception occurs, print the relevant exception information and return "the service is unavailable."

Start the project Spring-cloud-producer-2, this time the service center will have two spring-cloud-producer projects, we restart the Zuul project. Then manually close the Spring-cloud-producer-2 project, multiple access addresses: http://localhost:8888/spring-cloud-producer/hello?name=neo&token=xx , will be returned alternately:

Hello Neo, This is the first messgethe service is unavailable ....

As can be seen from the returned results: The SPRING-CLOUD-PRODUCER-2 project has been fused and returned:The service is unavailable.

Zuul currently only supports service-level fuses and does not support specific URLs for fusing.

Second, routing retry

sometimes because of the network or other reasons, the service may be temporarily unavailable, this time we want to be able to retry the service , Zuul also help us achieve this function, we need to combine with the spring Retry to achieve. Let's take a demonstration of the above project as an example.

Add Spring Retry Dependency

First, add Spring Retry dependencies to the Spring-cloud-zuul project.

< Dependency >    < groupId >org.springframework.retry</groupId>    <  Artifactid>spring-retry</artifactid></  dependency>

Open Zuul Retry

Configure enable Zuul Retry in the configuration file

#是否开启重试功能zuul.retryable=true#对当前服务的重试次数ribbon. maxautoretries=2# the number of times the same server was switched ribbon.maxautoretriesnextserver=0

This allows us to turn on the retry function of the Zuul.

Test

We retrofit the spring-cloud-producer-2, add timing to the Hello method, and print the parameters at the beginning of the request.

@RequestMapping ("/hello") public String Index (@RequestParam String name) {    Logger.info ( "Request", "name is" +name    ); Try {        thread.sleep (1000000);    } Catch (Exception e) {        logger.error ("Hello, error", e);    }     return "Hello" +name+ ", this is the Messge";}

Restart the spring-cloud-producer-2 and Spring-cloud-zuul projects.

Access address: When http://localhost:8888/spring-cloud-producer/hello?name=neo&token=xx the page returns: The service is unavailable. when viewing the item spring-cloud-producer-2 the background log is as follows:

2018-01-22 19:50:32.401  INFO 19488---[io-9001-exec-14] O.s.c.n.z.f.route.fallbackprovider       : Request Name is Neo2018-01-22 19:50:33.402  INFO 19488---[io-9001-exec-15] O.s.c.n.z.f.route.fallbackprovider       : Request the name is Neo2018-01-22 19:50:34.404  INFO 19488---[io-9001-exec-16] O.s.c.n.z.f.route.fallbackprovider       : Request name is Neo

The description made three requests, that is, two retries. This also verifies our configuration information and completes the retry function of the Zuul.

Attention

Open retry is problematic in some cases, such as when the pressure is too high and one instance stops responding, the route transfers traffic to another instance, which is likely to cause all instances of the end to be overwhelmed. In the final analysis, one of the functions of a circuit breaker is to prevent failure or pressure spread. With retry, a circuit breaker can only work if all instances of the service are not operational. At such times, the form of a circuit-breaker is more like providing a friendly error message, or pretending that the service is operating in a false sense to the user.

Without retry, using only load balancing and fusing, you must consider whether you can accept a short fuse between a single service instance shutdown and the Eureka Refresh Service list. If it is acceptable, you do not need to use retry.

transferred from : http://www.ityouknow.com/springcloud/2018/01/20/spring-cloud-zuul.html

Nine, Springcloud service Gateway Zuul (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.