In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn SpringCloud Fegin deeply". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to learn SpringCloud Fegin deeply".
Before we met Fegin,
In our daily work, we often encounter API that wants to call internal API or other third-party services. Before we encounter Fegin, we will basically use the following ways.
1.HttpURLConnection
Brief introduction:
URLConnection is an abstract class that has two direct subclasses, HttpURLConnection and JarURLConnection.
Another important class is URL, and usually URL can generate an instance of URL pointing to a specific address by passing a parameter of type String to the constructor.
Each HttpURLConnection instance can be used to generate a single request, but other instances can transparently share the underlying network connected to the HTTP server.
Calling the close () method on the InputStream or OutputStream of the HttpURLConnection after the request releases the network resources associated with this instance, but has no effect on the shared persistent connection.
If the persistent connection is idle when disconnect () is called, the underlying socket may be closed.
Any network connection needs to go through socket to connect, and HttpURLConnection does not need to set up socket, so HttpURLConnection is not a low-level connection, but a request on the underlying connection.
This is why HttpURLConneciton is just an abstract class and cannot be instantiated by itself. HttpURLConnection can only create concrete instances through the URL.openConnection () method.
Although the underlying network connection can be shared by multiple HttpURLConnection instances, each HttpURLConnection instance can send only one request.
After the request ends, you should call the InputStream of the HttpURLConnection instance or the close () method of OutputStream to release the requested network resources, but this is not useful for persistent connections. For persistent connections, you have to turn off the socket of the underlying connection with the disconnect () method.
HttpURLConnection request response process:
2.HttpClient
Brief introduction:
HttpClient is a subproject under Apache Jakarta Common that can be used to provide efficient, up-to-date, feature-rich client programming toolkits that support the HTTP protocol, and it supports the latest versions and recommendations of the HTTP protocol.
It is a HTTP communication library and a toolkit, so it provides only a subset of the functionality expected by general-purpose browser applications.
The most fundamental difference between HttpClient and the browser is that there is no user interface in HttpClient, and the browser needs a rendering engine to display the page. And explain user input (such as how to respond after a mouse click to display somewhere on the page, calculate how to display HTML pages, cascading stylesheets and images, javascript interpreter runs javascript code embedded in or referenced from HTML pages, events from the user interface are passed to the javascript interpreter for processing, etc.).
HttpClient can only be used to transmit and receive HTTP messages programmatically through its API, and it is completely agnostic to the content.
HttpClient still has many good features (excerpted from Apache HttpClient's official website):
1. Based on standards, pure java language. HTTP1.0 and HTTP1.1 are implemented
two。 All the methods of HTTP (GET, POST and other 7 methods) are implemented with extensible object-oriented structure.
3. Support for HTTPS protocol
4. Establish a transparent connection through a HTTP proxy
5. Using CONNECT method to establish tunnel HTTPS connection through HTTP proxy
6.Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos authentication scheme
7. Plug-in custom authentication scheme
8. A portable and reliable socket factory makes it easier to use third-party solutions
9. Connection manager supports multithreaded applications; supports setting the maximum number of connections, and supports setting the maximum number of connections per host, discovering and closing expired connections
10. Automatic processing of Cookie in Set-Cookie
11. Plug-in custom Cookie policy
The output stream of 12.Request prevents the contents of the stream from being buffered directly to the socket server
The input stream of 13.Response can effectively read the corresponding content directly from the socket server.
14. Using KeepAlive to maintain persistent connections in HTTP1.0 and HTTP1.1
15. Get the response code and headers sent by the server directly
16. Set the ability to time out a connection
17. Experimental support for HTTP1.1 response caching
18. The source code is freely available based on Apache License.
Get Demo
Public static void main (String [] args) throws IOException {/ / 1. Open the browser CloseableHttpClient httpClient = HttpClients.createDefault (); / / 2. Declare the get request HttpGet httpGet = new HttpGet ("http://www.baidu.com/s?wd=java"); / / 3. Send request CloseableHttpResponse response = httpClient.execute (httpGet); / / 4. Judge the status code if (response.getStatusLine (). GetStatusCode () = = 200) {HttpEntity entity = response.getEntity (); / / use the utility class EntityUtils to take the content represented by the entity from the response and convert it into the string String string = EntityUtils.toString (entity, "utf-8"); System.out.println (string);} / / 5. Close the resource response.close (); httpClient.close ();}
Post Demo
Public static void main (String [] args) throws IOException {/ / 1. Open the browser CloseableHttpClient httpClient = HttpClients.createDefault (); / / 2. Declare the get request HttpPost httpPost = new HttpPost ("https://www.oschina.net/"); / / 3. Open source China restricts browsers to access httpPost.addHeader ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36") in post requests for security and prevention of malicious attacks. Judge status code List parameters = new ArrayList (0); parameters.add (new BasicNameValuePair ("scope", "project")); parameters.add (new BasicNameValuePair ("Q", "java")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (parameters, "UTF-8"); httpPost.setEntity (formEntity); / / 5. Send request CloseableHttpResponse response = httpClient.execute (httpPost); if (response.getStatusLine (). GetStatusCode () = = 200) {HttpEntity entity = response.getEntity (); String string = EntityUtils.toString (entity, "utf-8"); System.out.println (string);} / / 6. Close the resource response.close (); httpClient.close ();}
3.OKHttp
I recommend an article to you, which I think is very good.
Https://blog.csdn.net/iispring/article/details/51661195?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.channel_param
4.RestTemplate
Brief introduction:
RestTemplate is a HTTP request tool supported from Spring3.0. It provides templates for common REST request schemes, such as GET request, POST request, PUT request, DELETE request and some general request execution methods exchange and execute.
RestTemplate inherits from InterceptingHttpAccessor and implements the RestOperations interface, where the RestOperations interface defines basic RESTful operations, all of which are implemented in RestTemplate. Next, let's look at the use of these methods of operation.
Get Demo
Public void doHttpGetTest () throws UnsupportedEncodingException {/ /-- > get Rest client instance RestTemplate restTemplate = new RestTemplate () / /-- > resolve (response data may be) the problem of Chinese garbled List converter = new StringHttpMessageConverter (StandardCharsets.UTF_8); converterList.add (1, converter); / / add a new converter (note: convert sequence error will lead to failure) restTemplate.setMessageConverters (converterList) / /-- > (optional setting) request header information / / HttpHeaders implements the MultiValueMap interface HttpHeaders httpHeaders = new HttpHeaders (); / / add some data httpHeaders.add to the request header ("Java learning tribe", "this is an official account for learning technology!") / /-- > Note: when a GET request creates a HttpEntity, you can input null into the request body. You can choose the type of the request body as long as the type of the request body is consistent with the generics of the HttpEntity class. String httpBody = null; HttpEntity httpEntity = new HttpEntity (httpBody, httpHeaders) / /-- > URI StringBuffer paramsURL = new StringBuffer ("http://127.0.0.1:8080/restTemplate/doHttpGet"); / / character data is best encoding In this way, some special characters can be passed (for example, the parameter value of flag is "&", which cannot be passed without encoding) paramsURL.append ("? flag=" + URLEncoder.encode ("&", "utf-8")); URI uri = URI.create (paramsURL.toString ()) / /-- > execute the request and return the result / / the generics here correspond to the response body data type; / / that is, the data assembly of the response body is specified here as String ResponseEntity response = restTemplate.exchange (uri, HttpMethod.GET, httpEntity, String.class) / /-> response information / / response code, such as: 401,302,404,500,200 System.err.println (response.getStatusCodeValue ()); Gson gson = new Gson (); / / response header System.err.println (gson.toJson (response.getHeaders () / / response body if (response.hasBody ()) {System.err.println (response.getBody ());}}
Post Demo
Public void doHttpPostTest () throws UnsupportedEncodingException {/ / get Rest client instance RestTemplate restTemplate = new RestTemplate (); / / solve the problem of garbled code in Chinese (response data may) List converter = new StringHttpMessageConverter (StandardCharsets.UTF_8); / / add a new converter (note: convert sequence error will lead to failure) converterList.add (1, converter); restTemplate.setMessageConverters (converterList) / / (optional setting) request header information / / HttpHeaders implements the MultiValueMap interface HttpHeaders httpHeaders = new HttpHeaders (); / / sets contentType httpHeaders.setContentType (MediaType.APPLICATION_JSON_UTF8); / / adds some data httpHeaders.add to the request header ("Java learning tribe", "this is an official account for learning java!") / / put the request header and request body data into the HttpEntity / / you can choose the type of the request body; as long as you ensure that the type of the request body is consistent with the generics of the HttpEntity class / / A json string is handwritten as the request body data (in actual development, you can use fastjson, gson and other tools to convert the data into json strings) String httpBody = "{\" motto\ ":\" java is so powerful! \ "}"; HttpEntity httpEntity = new HttpEntity (httpBody, httpHeaders); / / URI StringBuffer paramsURL = new StringBuffer ("http://127.0.0.1:8080/restTemplate/doHttpPost"); / / character data is best encoding In this way, some special characters can be passed (for example, the parameter value of flag is "&", which cannot be passed without encoding) paramsURL.append ("? flag=" + URLEncoder.encode ("&", "utf-8")); URI uri = URI.create (paramsURL.toString ()); / / execute the request and return the result / / the generics here correspond to the response body data type. That is, the data assembly of the specified response body here is String ResponseEntity response = restTemplate.exchange (uri, HttpMethod.POST, httpEntity, String.class); / / response information / / response code, such as: System.err.println (response.getStatusCodeValue ()); Gson gson = new Gson (); / / response header System.err.println (gson.toJson (response.getHeaders () / / response body if (response.hasBody ()) {System.err.println (response.getBody ());}}
This is only a brief introduction to RestTemplate's Get request and Post request, and does not delve into RestTemplate and other forms of requests that implement RestTemplate.
Because I can't wait to have a beautiful encounter with Fegin.
A beautiful encounter with Fegin
What is Fegin?
Feign is a declarative, templated HTTP client developed by Netflix, and Feign can help us call HTTP API more quickly and gracefully.
In Spring Cloud, using Feign is simple: create an interface, add some annotations to the interface, and the code is done. Feign supports a variety of annotations, such as Feign's native annotations or JAX-RS annotations.
Spring Cloud has enhanced Feign to enable Feign to support Spring MVC annotations and integrate Ribbon and Eureka to make Feign easier to use.
Spring Cloud Feign is based on the Netflix feign implementation and integrates Spring Cloud Ribbon and Spring Cloud Hystrix. In addition to the powerful capabilities of both, it also provides a declarative way to define Web services clients.
Spring Cloud Feign helps us define and implement the definition of dependent service interfaces. Under the implementation of Spring Cloud feign, you only need to create an interface and configure it with annotations to complete the interface binding of the service provider, which simplifies the development of self-encapsulating service invocation client when using Spring Cloud Ribbon.
Spring Cloud Feign has pluggable annotation support, supporting Feign annotations, JAX-RS annotations, and Spring MVC annotations.
Feign is actually a layer of encapsulation for ordinary HTTP clients, and its purpose is to reduce integration costs and improve reliability. Feign supports three HTTP clients, including HttpURLConnection, Apache HttpClient and Square OkHttp that come with JDK, and Apache HttpClient is used by default.
What is the purpose of Fegin?
Feign can hide Rest's request and pretend to be like SpringMVC's Controller.
You no longer have to splice url, stitching parameters and other operations by yourself, and leave everything to Feign.
Netflix Feign or Open Feign?
On this time node, many people are confused about the "two" Feign, and they don't know the difference and connection, which will be informed in this article. First of all, it needs to be clear: they belong to the same thing, and Feign is an open source component of Netflix. In view of the differences, the following is divided into these aspects to make a comparison
1. Differences in GAV coordinates:
Com.netflix.feignfeign-coreio.github.openfeignfeign-core
2. Address differences on the official website: https://github.com/Netflix/feign and https://github.com/OpenFeign/feign. But now visiting https://github.com/Netflix/feign has been redirected to the latter.
3. Publishing history:
Netflix Feign1.0.0 was released in 2013.6 and its last version, 8.18.0, was released in July 2016.
Open Feign: the first version is version 9.0.0, which was released in July 2016 and has been released ever since (not stopped)
From the above three characteristics, you can clearly see the difference and relationship between the two, a simple understanding: Netflix Feign just changed its name to Open Feign, and then the Open Feign project continues to develop on its basis.
It was called Netflix Feign before version 9.0, but it has been renamed Open Feign since version 9.0.
Note, however, that although the GAV has completely changed, there is no change in the package name of the source code and the core API, so throwing has good backward compatibility (not 100% downward compatibility).
Spring-cloud-starter-feign or spring-cloud-starter-openfeign?
The differences between them are similar to those described above and are illustrated in several aspects:
1. Differences in GAV coordinates:
Org.springframework.cloudspring-cloud-starter-feignorg.springframework.cloudspring-cloud-starter-openfeign
History of publication:
Spring-cloud-starter-feign:2015.3 releases version 1.0.0, the last version of the 2019.5.23 publisher 1.4.7.RELEASE
It is worth noting that since 1.4.0.RELEASE, its 1.4.x release track is exactly the same as the 1.4.x release track below.
Spring-cloud-starter-openfeign:2017.11 released its first version, version number: 1.4.0.RELEASE. It is still being updated, and the latest version is 2.2.1.RELEASE.
Note: 1.4.7.RELEASE is the final version of Feign for the whole Spring Cloud1.x, and version 2.x is still under continuous maintenance and update.
Note: the old spring-cloud-starter-feign has abandoned Netflix feign and made full use of the newer Open Feign version since 1.2.0.RELEASE, while spring-cloud-starter-openfeign has nothing to do with Netflix Feign.
For the version, it can be roughly understood that spring-cloud-starter-openfeign is prepared for Spring Cloud2.x, but has maintained compatibility with 1.x for a period of time. Spring-cloud-starter-feign is designed to serve Spring Cloud1.x.
Core API package name: the large version upgrade of Spring Cloud has downward incompatibility, which is also reflected in Feign:
@ FeignClient Note:
Note: 1.x here refers not only to feign, but also to version 1.4.x of openfeign.
The 1.x version package name is org.springframework.cloud.netflix.feign.FeignClient, and the Jar is spring-cloud-netflix-core
The 2.x version package name is org.springframework.cloud.openfeign.FeignClient, and the Jar is spring-cloud-openfeign-core.
@ EnableFeignClients Note: the difference is the same as above
-quoted from: https://cloud.tencent.com/developer/article/1588509
Acquaintance with Fegin
Nine components of Fegin
1. Annotation translator Contract
As we all know, in Feign, you can call a remote Http API by defining an API interface. When defining a call to Client, you need to add some annotations to describe the basic information of calling API, such as whether the request type is GET or POST, and what the request URI is.
Contract allows users to customize the annotation translator to parse the annotation information.
Contract determines which annotations can be marked as valid on the interface / interface method, and extracts valid information and assembles it into MethodMetadata meta-information.
The most typical application scenario is to use Feign in Spring Cloud. We can use the annotations of Spring MVC to define the client of Feign, because our own SpringMvcContract is implemented in Spring Cloud OpenFeign.
2.Encoder encoder
The information of our request is encoded into the Http request body by the specified coding method for transmission.
3.QueryMapEncoder parameter query encoder
QueryMapEncoder is an encoder for querying the parameters of entity classes, which can generate the corresponding query parameters based on QueryMapEncoder.
4.Decoder decoder
Decoder decoder acts on Response, which is used to parse the response of Http request and extract useful information data.
The Decoder decoder decodes the HTTP response feign.Response into a single object of a specified type.
5.ErrorDecoder error decoder
The ErrorDecoder error decoder is a decoder used in the event of errors or exceptions, allowing you to perform special handling of exceptions.
6.Logger logging
A logger abstracted by Feign itself, responsible for logging in Feign, can specify the level of Logger and customize the output of the log.
7.Client request execution component
Client is the component responsible for the execution of HTTP requests. After the request information is encapsulated by Feign, it will be handed over to Client for execution.
By default, the HttpURLConnection used for calls between services does not use connection pooling, and HttpURLConnection connections are created each time it is used, which is very inefficient.
To improve efficiency through connection pooling, we can use appache httpclient as the connection pooling. Of course, configuring OkHttpClient connection pooling is a similar approach.
8.Retryer retry component
Retry is not a retry after an error is reported, but when the load balancer client finds that the remote request instance is unreachable, it retries to request other instances.
Feign itself has the ability to retry. In early Spring Cloud, Feign used feign.Retryer.Default#Default () to retry five times.
But Feign integrates with Ribbon,Ribbon and has the ability to retry, which can lead to behavioral confusion.
Spring Cloud is aware of this problem and has made improvements by changing the retry of Feign to feign.Retryer#NEVER_RETRY. If you need to retry with Feign, you only need to use Ribbon's retry configuration.
9.RequestInterceptor request interceptor
By implementing the apply method of the RequestInterceptor API, we can set some extended parameter information or modify the request header information before the request is executed, because feign will call the apply method of the API before sending the request, so we can also record the time when the request is sent by implementing this API.
The execution process of Fegin
Sentimental with Fegin
The use of native API for Fegin
Public interface GitHub {@ RequestLine ("GET / repos/ {owner} / {repo} / contributors") List contributors (@ Param ("owner") String owner, @ Param ("repo") String repository); class Contributor {String login; int contributions }} public class MyApp {public static void main (String [] args) {GitHub github = Feign.builder () .decoder (new GsonDecoder ()) .target (GitHub.class, "https://api.github.com"); / * The owner and repository parameters will be used to expand the owner and repo expressions * defined in the RequestLine. * * the resulting uri will be https://api.github.com/repos/OpenFeign/feign/contributors * / github.contributors ("OpenFeign", "feign");}}
This code is my sample code from the GitHub home page of OpenFeign.
This is a list of GET requests, defining an interface for GitHub, which defines a query method and parameters. There is a @ RequestLine annotation on the method, which defines the request type and the corresponding parameter placeholder in the request URI,URI, the return value is the collection, and the corresponding return structure object is in the collection.
After we build the GitHub interface object through Feign's builder mode, we can call the contributors method directly through the GiuHub interface object, and then get the return result. Feign is called in the same way as in Dubbo, just like calling a local method.
To use native Feign to call API, you only need to use specific annotations to describe the API information of the call, which can be requested by GET or POST. What are the request parameters? What is the requested address? After defining this information, you can directly use the defined interface to call the corresponding remote API.
Fegin is used in conjunction with SpringCloud
1. First, create an OpenFeginClient module with the following pom.xml code:
Org.springframework.cloud spring-cloud-starter-netflix-eureka-server org.springframework.cloud spring-cloud-starter-openfeign
two。 Add @ EnableFeignClients to the startup class to enable Feign
Package com.javaer.study.openfeginclient;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.cloud.openfeign.EnableFeignClients / * * @ Author official account [Java Learning Tribe] * * follow the official account to obtain 4000G high-quality video resources * * learn more about Java backend, middleware, big data, microservice, distributed, big data and other learning materials * * / @ SpringBootApplication@EnableFeignClients@EnableEurekaClientpublic class OpenfeginclientApplication {public static void main (String [] args) {SpringApplication.run (OpenfeginclientApplication.class, args);}} 3. Configure appliation.yml to register with Eureka Server. Server: port: 8888spring: application: name: spring-cloud-feign-openClienteureka: client: service-url: defaultZone: http://localhost:8761/eureka/4. Declare a simple callable client for this application using @ FeignClient. For convenience, we still use Github's open api. Package com.javaer.study.openfeginclient;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam / * A callable client * * @ author topJavaer * official account: [Java Learning Tribe] * @ create 2020 11 10 * @ Version 1.0.0 * / / @ FeignClient is the specified client information note, which must be declared on the API. Url manually specifies the interface address of the client @ FeignClient (name = "github-client", url = "https://api.github.com")public interface GitHubApiClient {@ RequestMapping (value =" / search/repositories ", method = RequestMethod.GET) String searchRepositories (@ RequestParam (" Q ") String queryStr) }
5. Add test code
Package com.javaer.study.openfeginclient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/** * Test Class * * @ author topJavaer * official account: [Java Learning Tribe] * @ create 2020 11 10 * @ Version 1.0.0 * / @ RestControllerpublic class GitHubApiTest {@ Resource private GitHubApiClient gitHubApiClient @ RequestMapping ("/ search/github/repository") public String searchGithubRepositoryByName (@ RequestParam ("name") String repositoryName) {return gitHubApiClient.searchRepositories (repositoryName);}}
6. Finally, we start the Eureka Server we wrote when we talked about Eureka before, and then start the module.
Visit: http://localhost:8888/search/github/repository?name=spring-cloud-dubbo
The results are as follows:
The above is the basic process of Spring Cloud using OpenFegin, is not very simple, take a look, operation, immediately will, of course, if you want to in-depth understanding, only this is far from enough, or need everyone to continue to specialize in research, to explore in depth.
Fegin's core annotations @ FeignClient details
Package org.springframework.cloud.netflix.feign; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; @ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented public @ interface FeignClient {@ AliasFor ("name") String value () default "; @ Deprecated String serviceId () default" @ AliasFor ("value") String name () default ""; String qualifier () default ""; String url () default ""; boolean decode404 () default false; Class [] configuration () default {}; Class fallback () default void.class; Class fallbackFactory () default void.class; String path () default "; boolean primary () default true;}
Name: specify the name of the Feign Client. If the project uses the Ribbon,name attribute, it will be used as the name of the microservice for service discovery.
ServiceId: using serviceId for service discovery has been deprecated, so this configuration is not recommended.
Value: specify the serviceId of Feign Client. If the project uses Ribbon, serviceId will be used for service discovery. However, you can see that serviceId for service discovery has been abandoned, so this configuration is not recommended.
Qualifier: add comments @ Qualifier for Feign Client
Url: the absolute URL of the request address, or the resolved hostname
Decode404: when a common 404 error occurs in calling the feign client, whether to call decoder to decode the exception information is returned, otherwise FeignException is thrown.
Fallback: define the fault-tolerant processing class. When the call to the remote interface fails or times out, the fault-tolerant logic of the corresponding interface will be called. The class specified by fallback must implement the @ FeignClient marked interface. The method implemented is the fault-tolerant processing logic of the corresponding interface.
FallbackFactory: factory class, used to generate fallback class examples, through this property we can implement fault-tolerant logic common to each interface and reduce repetitive code.
Path: defines all method mappings of the current FeignClient with a uniform prefix.
Primary: whether to mark this Feign agent as a Primary Bean. Default is ture.
Core configuration of Fegin
There are two ways to configure Fegin.
One is the Java code configuration, which needs to be referenced by @ EnableFeignClients (defaultConfiguration = DefaultFeignConfiguration.java) at the main program startup portal.
The second is the direct profile configuration, which is configured in application.yml or application.properties.
What we should know is that if you configure Feign through Java code, and then configure Feign through a properties file, the configuration of Frign in the properties file will override the configuration of the Java code.
However, feign.client.default-to-properties=fasle can be configured to change the priority at which the Feign configuration takes effect.
This article mainly explains some daily configuration, through the configuration file.
Spring Cloud Feign supports GZIP compression of requests and responses to improve communication efficiency.
# enable GZIP compression configuration # request GZIP compression feign.compression.request.enable=true # respond to GIZP compression feign.compression.response.enable=true # compression supported mime type feign.compression.request.mime-types=text/xml Application/xml.application/json feign.compression.request.min-request-size=1024 # minimum size of compressed data
Feign provides an feign.logger instance for each FeignClient, which can be enabled in the configuration or in the java code.
NONE means that the log is not output. BASIC indicates that only the URL of the request method and the status code of the response and the time of execution are output. HEADERS outputs BASIC information and request header information. FULL outputs all the complete request information. Logging: level: com.javaer.study: debugfeign: client: config: # name of the service to be invoked java-master: loggerLevel: full
Timeout configuration of Fegin
Ribbon timeout configuration
When Read time out occurs in the system, it means that the Ribbon has timed out and needs to be controlled in the configuration file.
# Ribbon configuration ribbon: # connection timeout ConnectTimeout: 2000 # response timeout ReadTimeout: 5000
Hystrix timeout configuration
The higher version of Fegin Hystrix is turned off by default. The following configuration is required to enable:
# Feign configuration feign: # turn on circuit breaker (fuse) hystrix: enabled: true
In order to avoid timeout, we can configure our own timeout according to business conditions. Here, the circuit breaker time is 5000 / millisecond.
Note: it is recommended that the timeout of Ribbon is not greater than that of Hystrix.
# Hystrix configuration hystrix: # this will automatically configure a hook of the Hystrix concurrency policy plug-in, which will transfer the SecurityContext from the main thread to the command of Hystrix. # because Hystrix does not allow multiple Hystrix policies to be registered, you can declare HystrixConcurrencyStrategy # as a Spring bean to implement the extension. Spring Cloud will look up your implementation in the context of Spring and wrap it in its own plug-in. ShareSecurityContext: true command: default: circuitBreaker: # short circuit when this number of failures is reached within the configuration time window. By default, there are 20 requestVolumeThreshold: 1 # time values for triggering a short circuit. When this value is set to 5000, request # will be rejected within 5000 milliseconds after circuit break is triggered, that is, 5000 milliseconds before circuit will be turned off. By default, 5000 sleepWindowInMilliseconds: 15000 # forcibly turns on fuses. If this switch is turned on, all request is rejected. By default, false forceOpen: false # forces fuses to be turned off. If this switch is on, circuit will always turn off and ignore. Default false forceClosed: false execution: isolation: thread: # fuse timeout Default: 1000 / millisecond timeoutInMilliseconds: 5000
Inheritance feature of Fegin
Spring Cloud Feign provides inheritance feature, the so-called inheritance feature is to extract some common operations into a parent interface, so as to inherit the operations in the parent interface, reduce the repeated development of code, and save development costs.
1. Advantages
The definition of the interface can be stripped from the Controller, and the sharing of the interface definition can be easily realized with the Maven private repository. Instead of copying and pasting the interface for binding, the interface binding during the construction period can be realized, thus effectively reducing the binding configuration of the service client.
2. Shortcomings
Because the interface has established dependencies during the construction, then the interface change will have an impact on the project construction, and the service provider may modify an interface definition, which will directly lead to the construction failure of the client project.
Therefore, if the development team realizes interface sharing through this method, it is recommended that the object-oriented principle of opening and closing should be strictly observed during the development review, and the compatibility between the front and back versions should be done as much as possible, so as to prevent the consequences of affecting the whole body. Increase the team's unnecessary maintenance workload.
Fegin retry mechanism
The request retry mechanism is implemented by default in Spring Cloud Feign. The following configuration is used: when a failed request is accessed, it will try to access the current instance again (the number of times is configured by MaxAutoRetries). If not, another instance will be accessed. If not, another instance will be accessed (the number of replacements will be configured by MaxAutoRetriesNextServer). If it still fails, a failure message will be returned.
Note: Ribbon timeout and Hystrix timeout are two concepts. In order to make the above implementation effective, we need to make the timeout of Hystrix greater than that of Ribbon, otherwise the Hystrix command will be directly fused after the timeout of the command, and the retry mechanism will not make any sense.
# the timeout of the circuit breaker needs to be greater than that of Ribbon, otherwise it will not trigger the retry hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000# request connection timeout fegin-service.ribbon.ConnectTimeout=500# request processing timeout fegin-service.ribbon.ReadTimeout=1000# retries all requests (whether all operations are retried If false, only get requests to retry) the number of retries of the current instance fegin-service.ribbon.MaxAutoRetries=1# switch instance fegin-service.ribbon.MaxAutoRetriesNextServer=2 so far, I believe you have a deeper understanding of "how to learn SpringCloud Fegin", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.