Fallback Method ClassThe Getroute method is implemented, and the return Helloworld-provider represents the fallback class for the Helloworld-provider service, implements the Fallbackresponse method, and indicates the specific content returned by the fallback method
Package Org.lixue.zuul;
??
Import Org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
Import org.springframework.http.HttpHeaders;
Import Org.springframework.http.HttpStatus;
Import Org.springframework.http.MediaType;
Import Org.springframework.http.client.ClientHttpResponse;
??
Import Java.io.ByteArrayInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
??
Public class Helloworldfallback implements zuulfallbackprovider{
@Override
Public String Getroute () {
return"Helloworld-provider" ;
}
??
@Override
Public clienthttpresponse Fallbackresponse () {
return new Clienthttpresponse () {
@Override
Public httpstatus Getstatuscode ()throwsioexception{
return Httpstatus. OK;
}
??
@Override
public int Getrawstatuscode ()throwsioexception{
return Httpstatus. OK. Value ();
}
??
@Override
Public String getstatustext ()throwsioexception{
return H Ttpstatus. OK. toString ();
}
??
@Override
Public void Close () {
??
}
??
@Override
Public InputStream getbody () throws ioexception{
return new Bytearrayinputstream ("fallback". GetBytes ());
}
??
@Override
Public httpheaders getheaders () {
Httpheaders headers=new httpheaders ();
Headers.setcontenttype (mediatype. Text_plain );
return headers;
}
};
}
}
??
Zuul Configuration ClassCreate a configuration class and create an instance Bean of the fallback class in the configuration class
Package Org.lixue.zuul;
??
Import org.springframework.context.annotation. Bean;
Import org.springframework.context.annotation. Configuration;
??
@Configuration
Public class zuulfallbackconfiguration{
??
@Bean
Public helloworldfallback Helloworldfallback () {
return new Helloworldfallback ();
}
}
??
Test validationthe project relies on a eureka-sserver, Service-provider service that starts Eureka-server and Service-provider services first, and then starts Spring-cloud-zuul-microservices Service, Access to http://localhost:9200/hello/speaks?names=123 address, you can see the normal return, as follows:
{"123": "Hello World 123 port=8080"}
At this point, the Service-provider service is turned off again, and you can see that the Service-provider service is inaccessible and the data for the fallback method is returned, as follows:
Fallback