Send HTTP requests using Feign

Send HTTP requests using Feign

In the usual HTTP calls, the RestTemplate provided by the government has always been used for remote calls. This call method redundancies the assembly code into the normal business code, which is not elegant enough. Therefore, after contacting Feign, consider using Feign as an HTTP sending basis for remote calls.


Let's take a look at how it is used.

Introduce dependency

First, we need to introduce Feign's basic dependencies into the project, because we only use Feign's remote function, so we only introduce basic dependencies.


In addition, in the project, we also customized JSON conversion and log settings, so we also need to introduce these third-party dependencies, as shown below.

      <!-- feign -->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>10.10.1</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-gson</artifactId>
            <version>10.10.1</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-slf4j</artifactId>
            <version>10.10.1</version>
        </dependency>

Sending path and method settings

Then, because Feign is a declarative call, we need to configure the sending interface path and sending interface definition. See the following example.

    @RequestLine("GET /user/getone?arkOrgId={arkOrgId}&userId={userId}")
    JSONObject getOneStaff(@Param("arkOrgId") String arkOrgId,@Param("userId") String userId);

    @RequestLine("POST /user/add")
    @Headers("Content-Type: application/json")
    @Body("{body}")
    JSONObject saveStaff(@Param("body") SaveEmployeeDTO saveEmployeeDTO);

In the code examples, we define two sending examples, one is GET request and the other is POST request. Next, let's take a look at the role of the code.

  • @RequestLine: define the sending method and sending interface definition, in which GET and POST are used to define the sending method, and then write the service path after the space (context path and domain name or ip port number are configured elsewhere);
  • {}: used as a placeholder to dynamically fill in the required parameters;
  • @Param: used to match placeholders in URI;
  • @Headers ("content type: application / json"): build the request header. In the POST request, you need to declare that the sending format of the request is json;
  • @Body: POST request, the request body needs to be marked;
  • JSONObject: in this example, a general json object is used to receive, which is convenient and unified. In your own code, you can also define an accepting entity class to accept, and the function is the same.

For a POST request, you need to rewrite the toString() method in the entity to make it a JSON string after calling the method when sending. For details, see Tips later.

Define sending client

@Configuration
public class FeignConfig {
    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    @Value("${staff.base.url}")
    private String staffBaseUrl;
    @Bean
    public StaffFeignService staffFeignService() {
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(DATE_TIME_FORMAT);
        return Feign.builder()
                .retryer(closeFeignRetry())
                .decoder(new GsonDecoder(builder.create()))
                .encoder(new GsonEncoder())
                .logger(new Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .target(StaffFeignService.class, staffBaseUrl);
    }
    /**
     * Turn off feign's failure retry function
     */
    @Bean
    public Retryer closeFeignRetry() {
        return Retryer.NEVER_RETRY;
    }

    @Bean
    public Request.Options options() {
        return new Request.Options(15000, 30000);
    }
}

Next, let's define the sending client.


First, we use @ Value to dynamically add routes, so that we can add context path according to the attributes in the configuration file, so as to be extensible.


Then, many configurations of Feign can be in DIY according to their own project needs. Therefore, here, we configure GSON codec for encoding and decoding, and set full printing at log level. Use this setting to generate a Feign client.

Feign official document , there are detailed configuration instructions in the official documents, which can be used according to their own needs.

use

@Autowired
StaffFeignService staffFeignService;

// get request
JSONObject saveSingleQrCode = staffFeignService.saveSingleQrCode(userId);

// post request
SaveMultiQrCodesDTO saveMultiQrCodesDTO = new SaveMultiQrCodesDTO();;
JSONObject saveMultiQrCodes = staffFeignService.saveMultiQrCodes(saveMultiQrCodesDTO);

In this way, the corresponding request can be sent.

Tips

Record some key points in use that need attention.

Override toString() method

When sending JSON, you need to rewrite the toString() method, otherwise the receiver will be unable to parse with JSON.

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

Asynchronous client

Sometimes, we use asynchronous sending, which does not affect our main business. Feign also supports this configuration.

    @Bean
    public IHermesFeignService hermesFeignService() {
        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(DATE_TIME_FORMAT);
        return AsyncFeign.asyncBuilder()
                .decoder(new GsonDecoder(builder.create()))
                .encoder(new GsonEncoder(builder.create()))
                .logger(new Slf4jLogger())
                .logLevel(Logger.Level.FULL)
                .target(IHermesFeignService.class, hermesBaseUrl);
    }

The key point is to use asyncfeign.com when building Feign Asyncbuilder().


Screenshot of official account




The article was first updated on the official account "iceWang". Interested friends can follow the official account and see the knowledge points shared by the author at the first time. Thank you! Refill!

Tags: Java Spring

Posted by duclet on Fri, 06 May 2022 15:05:17 +0300