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 call Feign remotely in SpringCloud

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

Share

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

This article will explain in detail how to call Feign remotely in SpringCloud. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Preface

Let's take a look at the code that we used to make remote calls using RestTemplate:

Here are a few questions:

The readability of code is poor and the programming experience is not uniform

URL with complex parameters is difficult to maintain

Feign is a declarative http client. Its function is to help us elegantly implement the sending of http requests and solve the problems mentioned above.

1.Feign substitutes for RestTemplate1.1 to introduce dependency

We introduce the dependency of feign in the pom file of the order-service service:

Org.springframework.cloud spring-cloud-starter-openfeign1.2 add comment

Add comments to the startup class of order-service to enable the function of Feign:

1.3 clients for writing Feign

Create a new interface in order-service, as follows:

FeignClient ("userservice") public interface UserClient {@ GetMapping ("/ user/ {id}") User findById (@ PathVariable ("id") Long id);}

This client mainly declares remote invocation information based on SpringMVC annotations, such as:

Service name: userservice

Request method: GET

Request path: / user/ {id}

Request parameter: Long id

Return value type: User

In this way, Feign can help us send http requests without having to use RestTemplate to send them.

1.4 Test

Modify the queryOrderById method in the OrderService class in order-service to use the Feign client instead of RestTemplate:

1.5 Summary

To use Feign:

① introduces dependency

② adds @ EnableFeignClients annotation

③ compiles FeignClient interface

④ uses the methods defined in FeignClient instead of RestTemplate

two。 Custom configuration

Feign can support many custom configurations, as shown in the following table:

In general, the default value is enough for us to use. If you want to customize it, you only need to create a custom @ Bean to override the default Bean.

Take the log as an example to demonstrate how to customize the configuration:

2.1 configuration file mode

Modifying the log level of feign based on the configuration file can be specific to a single service:

Feign: client: config: userservice: # configuration for a microservice loggerLevel: FULL # log level

It is also available for all services:

Feign: client: config: default: # here default is the global configuration. If you write the service name, it is the configuration loggerLevel: FULL # log level of a microservice.

There are four levels of logging:

NONE: no log information is recorded, which is the default

BASIC: record only the method of the request, URL, and the response status code and execution time

HEADERS: additional header information of request and response is recorded on the basis of BASIC

FULL: record the details of all requests and responses, including header information, request body, metadata

2.2 Java code mode

You can also modify the log level based on Java code, first declaring a class, and then declaring an object of Logger.Level:

Public class DefalutFeignConfiguration {@ Bean public Logger.Level feignLogLevel () {return Logger.Level.BASIC; / / log level is BASIC}}

If you want to take effect globally, put it in the @ EnableFeignClients annotation of the startup class:

@ EnableFeignClients (defaultConfiguration = DefaultFeignConfiguration .class)

If it is locally effective, put it in the corresponding @ FeignClient annotation:

@ FeignClient (value = "userservice", configuration = DefaultFeignConfiguration .class) 3.Feign usage optimization

The underlying Feign initiates http requests and relies on other frameworks. Its underlying client implementation includes:

URLConnection: default implementation, connection pooling is not supported

Apache HttpClient: supports connection pooling

OKHttp: supports connection pooling

So the main way to improve the performance of Feign is to use connection pooling instead of the default URLConnection.

Here we use Apache's HttpClient to demonstrate:

1) introduce dependency

Introduce Apache's HttpClient dependency into the pom file of order-service:

Io.github.openfeign feign-httpclient

2) configure connection pooling

Add a configuration to the application.yml of order-service:

Feign: client: config: default: # default global configuration loggerLevel: BASIC # log level, BASIC is the basic request and response information httpclient: enabled: true # enable feign support for HttpClient max-connections: 200 # maximum number of connections max-connections-per-route: 50 # maximum number of connections per path

Summarize the optimizations of Feign:

Try to use basic at the log level.

Use HttpClient or OKHttp instead of URLConnection

① introduces feign-httpClient dependency

② configuration file enables httpClient function and sets connection pool parameters

4. Best practic

The so-called best practice is the experience summed up in the use process, the best way to use it.

Self-study observation shows that the client side of Feign is very similar to the controller code of the service provider:

Feign client:

UserController:

Is there a way to simplify this repetitive coding?

4.1 inheritance mode

The same code can be shared through inheritance:

1. Define an API interface, use definition methods, and make declarations based on SpringMVC annotations

Both 2.Feign client and Controller integrate and change the interface.

Advantages:

simple

Code sharing is realized.

Disadvantages:

Tight coupling between service provider and service consumer

Annotation mappings in parameter lists are not inherited, so methods, parameter lists, and comments must be declared again in Controller

4.2 extraction mode

The Client of Feign is extracted as a separate module, and the interface-related POJO and default Feign configuration are put into this module and provided to all consumers.

For example, the default configurations of UserClient, User, and Feign are all extracted into a feign-api package, and all microservices refer to the dependency package, and you can directly use the

4.3 implement best practice extraction based on extraction

First create a module and name it feign-api:

Project structure:

Then introduce feign's starter dependency in feign-api:

Org.springframework.cloud spring-cloud-starter-openfeign

Then, the UserClient, User, and DefaultFeignConfiguration written in order-service are copied to the feign-api project

Using feign-api in order-service

First, delete UserClient, User, DefaultFeignConfiguration and other classes or interfaces in order-service

Introduce feign-api dependencies into the pom file of order-service:

Com.xn2001.feign feign-api 1.0

Modify all the guided packages related to the above three components in order-service to import the packages in feign-api

Restart the test

After restarting, it was found that the service reported an error:

This is because UserClient is now under the cn.itcast.feign.clients package.

The @ EnableFeignClients annotation of order-service is under the cn.itcast.order package and is not in the same package, so UserClient cannot be scanned.

Resolve scan packet problem

Method 1:

Specify which packages Feign should scan: (not recommended)

@ EnableFeignClients (basePackages = "cn.itcast.feign.clients")

Method 2:

Specify the Client interface to load:

@ EnableFeignClients (clients = {UserClient.class}) this is the end of the article on "how to call Feign remotely in SpringCloud". I hope the above content can be helpful to you so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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