Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use native Feign

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to use the native Feign, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

What is Feign?

Feign is a HTTP client based on Java developed by Netflix team, which draws lessons from Retrofit, JAXRS-2.0, WebSocket and other class libraries. With Feign, we can access HTTP API as easily as we call a method. This blog will show you how to use native Feign, note that it is native, not Spring encapsulated Feign.

To add, search for feign in the maven repository and we'll see two kinds of Feign: OpenFeign Feign and Netflix Feign. What's the difference between them? In a nutshell, the predecessor of OpenFeign Feign is Netflix Feign, and since Netflix Feign has been out of maintenance since 2016, it is recommended to use OpenFeign Feign.

Why use Feign

Why use HTTP client

First of all, because Feign itself is a HTTP client, the answer here is: why use HTTP client?

Assuming that we do not use HTTP client, the process of accessing HTTP API is roughly as follows. Isn't it quite complicated? It is very troublesome to operate socket directly, and we have to assemble and parse the message on the premise of being familiar with HTTP protocol. The complexity of the code can be imagined.

So, could the process be simpler?

We can find that in the above figure, the part of the red box is relatively universal, can we encapsulate this logic? Based on this thinking, there is HTTP client (the level of encapsulation varies depending on the class library).

So, why use HTTP client? To put it simply, it is to make it easier for us to access HTTP API.

Why use Feign

There are many other class libraries for HTTP client, such as Retrofit, JDK's native HttpURLConnection, Apache HttpClient, OkHttp, Spring's RestTemplate, and so on. I rarely recommend which specific class library to use, and if you really want to recommend Feign, it's mainly because of its excellent extensibility (not generally good, as you can see in later usage examples).

How to use Feign

The official documentation on how to use Feign is very detailed, which is relatively rare in the third-party class libraries I have seen.

The examples used in this article also refer to the official documentation.

Project environment description

Os:win 10

Jdk:1.8.0_231

Maven:3.6.3

IDE:Spring Tool Suite 4.6.1.RELEASE

Introduce dependency

Gson is introduced here because the entry example requires a json decoder.

11.2 io.github.openfeign feign-core ${feign.version} io.github.openfeign feign-gson ${feign.version} getting started example

In the getting started example, you use Feign to access the github interface to get all the contributors to the Feign repository.

As you can see from the following code, Feign essentially uses dynamic proxies to generate code that accesses HTTP API, and the process of defining HTTP API is a bit like defining advice.

/ / define HTTP APIinterface GitHub {@ RequestLine ("GET / repos/ {owner} / {repo} / contributors") / / @ RequestLine (value = "GET / repos/ {owner} / {repo} / contributors") DecodeSlash = false) / / Test escape "/", "+" / / @ RequestLine ("GET / repos/ {owner: [a-zA-Z] *} / {repo} / contributors") / / Test regular check / / @ Headers ("Accept: application/json") / / Test add header List contributors (@ Param ("owner") String owner, @ Param ("repo") String repo) } public static class Contributor {String login; int contributions;} public class MyApp {public static void main (String... Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new GsonDecoder ()) / / the return content is in json format So you need to use the json decoder / / .options (new Request.Options (10, TimeUnit.SECONDS, 60, TimeUnit.SECONDS, true)) / / configure timeout parameters, such as .target (GitHub.class, "https://api.github.com");"). / access HTTP API github.contributors ("OpenFeign", "feign") .stream () .map (contributor-> contributor.login + "(" + contributor.contributions + ")") .forEach (System.out::println);}} Personalized configuration

In addition to simplicity and convenience, Feign also has a big highlight, that is, it has excellent extensibility and can be customized to almost anything. The following is an official picture, which basically covers what Feign can expand. Each extension support has a corresponding adapter package. For example, when you change the decoder to jackson, you need to introduce an adapter package for io.github.openfeign:feign-jackson.

Notes to be replaced with Spring

In the getting started example, we use the annotations that come with Feign to define HTTP API. However, for many people who are used to Spring annotations, there is no doubt that the cost of learning needs to be increased. We naturally ask, can Feign support Spring annotations? The answer is yes. Feign supports not only Spring annotations, but also JAX-RS, SOAP, and so on.

Here is an example of using Sping annotations to define HTTP API. Note that the dependency of io.github.openfeign:feign-spring4 is introduced into the pom file.

/ / define HTTP APIinterface GitHub {@ GetMapping ("/ repos/ {owner} / {repo} / contributors") List contributors (@ RequestParam ("owner") String owner, @ RequestParam ("repo") String repo);} public class MyApp {public static void main (String...) Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new GsonDecoder ()) .contract (new SpringContract ()) / custom contract .target (GitHub.class, "https://api.github.com");}} custom decoder and encoder) used to access the HTTP API

In the getting started example, we use gson to parse json. So, what if I want to change it to jackson? Feign still provides support.

Note that the dependency of io.github.openfeign:feign-jackson is introduced into the pom file.

Public class MyApp {public static void main (String... Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new JacksonDecoder ()) / / custom decoder .encoder (new JacksonEncoder ()) / / custom encoder .target (GitHub.class, "https://api.github.com");}} customize the built-in HTTP client

The next customization is even more powerful. Feign itself, as a HTTP client, can actually support other HTTP client.

Here we use OkHttp as an example. Note that the dependency of io.github.openfeign:feign-okhttp is introduced into the pom file.

Public class MyApp {public static void main (String... Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new GsonDecoder ()) .client (new OkHttpClient ()) / / custom client .target (GitHub.class, "https://api.github.com");} custom interceptor) used to access the HTTP API

When we access the external interface, we sometimes need to bring some specific header, for example, application identity, token, we can do this in two ways: one is to use annotations to define the HTTP API, and the other is to use interceptors (more commonly used). In the following example, an interceptor is used to add a token request header to the request.

Public class MyInterceptor implements RequestInterceptor {@ Override public void apply (RequestTemplate template) {template.header ("token", LoginUtils.getCurrentToken ());}} public class MyApp {public static void main (String...) Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new GsonDecoder ()) .requestInterceptor (new MyInterceptor ()) .target (GitHub.class, "https://api.github.com");} custom retry) used to access HTTP API

By default, when Feign accesses HTTP API, if IOException is thrown, it will initiate a retry as a temporary network exception. In this case, Feign will use the default retry feign.Retryer.Default (up to 5 retries). If you do not want to enable retry, you can choose another retry feign.Retryer.NEVER_RETRY. Of course, we can also customize it.

Oddly enough, Feign determines whether to perform a retry by whether the retry's continueOrPropagate (RetryableException e) method throws a RetryableException, so why not use true or false to determine?

Note that the retry is used to determine whether or not to perform a retry and does not contain the logic of the retry itself.

Public class MyRetryer implements Retryer {int attempt = 0; @ Override public void continueOrPropagate (RetryableException e) {/ / if RetryableException is thrown, it will not continue to retry / / otherwise continue to retry if (attempt++ > = 3) {/ / retry throw e three times;}} @ Override public Retryer clone () {return this }} public class MyApp {public static void main (String... Args) {/ / get the proxy class GitHub github = Feign.builder () .decoder (new GsonDecoder ()) .retryer (new MyRetryer ()) / .retryer (Retryer.NEVER_RETRY) / / do not retry .promotionPropagationPolicy (ExceptionPropagationPolicy.UNWRAP) .target (GitHub.class) "https://api.github.com"); }} Thank you for reading this article carefully. I hope the article "how to use Native Feign" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report