Feign of spring cloud uses HTTP to request remote services
1. Introduction to Feign
In the spring Cloud Netflix stack, each microservice exposes its own service in the form of HTTP interface, so it must be used when calling remote services HTTP client. We can use JDK's native URLConnection, Apache's Http Client, Netty's asynchronous HTTP Client, and Spring's RestTemplate. However, the most convenient and elegant one to use is Feign.
Feign is a declarative, templated HTTP client. Using Feign in Spring Cloud, we can achieve the same coding experience as calling local methods when using HTTP to request remote services. Developers are completely unaware that this is a remote method, let alone an HTTP request.
2. How to use feign in spring cloud
1. Add dependencies
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-feign</artifactId> </dependency>
2. Create FeignClient
@FeignClient(name="SPRING-PRODUCER-SERVER/spring")public interface FeignUserClient { @RequestMapping( value = "/findAll/{name}",method = RequestMethod.GET) public List<SpringUser> findAll(@PathVariable("name") String name); @RequestMapping( value = "/findUserPost",method = RequestMethod.POST) public SpringUser findUserPost(@RequestBody SpringUser springUser);//复合类型好像默认是POST请求 }
@FeignClient(name="SPRING-PRODUCER-SERVER/spring"): used to notify the Feign component to proxy the interface (no need to write the interface Implementation), the name attribute specifies which service we want to call. Users can inject directly through @Autowired.
@RequestMapping indicates that a GET request needs to be sent to /group/{groupId} when calling this method.
@PathVariable has the same meaning as the corresponding annotation in SpringMVC.
Principle: When a Spring Cloud application is started, Feign will scan the interface marked with @FeignClient annotation, generate a proxy, and register it in the Spring container. When generating a proxy, Feign will create a RequetTemplate object for each interface method. This object encapsulates all the information required for HTTP requests. The request parameter name, request method and other information are determined in this process. Feign's templating is reflected in here.
3. Add annotations to the startup class
@Configuration @ComponentScan @EnableAutoConfiguration @EnableEurekaClient @EnableFeignClientspublic class SpringConsumerServerFeignApplication {public static void main(String[] args) { SpringApplication.run(SpringConsumerServerFeignApplication.class, args); } }
4. Configuration file application.yml
spring: application: name: spring-consumer-server-feign server: port: 8084 context-path: /spring #服务注册中心的配置内容,指定服务注册中心的位置 eureka: client: serviceUrl: defaultZone: http://user:password@localhost:8761/eureka/
三, Customized Feign configuration
1. Customized Configuration
@Configurationpublic class FooConfiguration { @Beanpublic Contract feignContract() {//这将SpringMvc Contract 替换为feign.Contract.Defaultreturn new feign.Contract.Default(); } }
2. Use customized Configuration
@FeignClient(name="SPRING-PRODUCER-SERVER/spring",configuration=FooConfiguration.class)public interface FeignUserClient { @RequestLine("GET /findAll/{name}")public List<SpringUser> findAll(@Param("name") String name); /* @RequestMapping( value = "/findAll/{name}",method = RequestMethod.GET) public List<SpringUser> findAll(@PathVariable("name") String name); @RequestMapping( value = "/findUserPost",method = RequestMethod.POST) public SpringUser findUserPost(@RequestBody SpringUser springUser);*/}
@RequestLine:是feign的注解 为每个创建的Feign客户端创建一个记录器。默认情况下,记录器的名称是用于创建Feign客户端的接口的完整类名。Feign日志记录仅响应DEBUG级别。logging.level.project.user.UserClient: DEBUG 在配置文件application.yml 中加入:
logging: level: com.jalja.org.spring.simple.dao.FeignUserClient: DEBUG
Add log level in the custom Configuration class
@Configurationpublic class FooConfiguration { /* @Bean public Contract feignContract() { //这将SpringMvc Contract 替换为feign.Contract.Default return new feign.Contract.Default(); }*/@Bean Logger.Level feignLoggerLevel() {//设置日志return Logger.Level.FULL; } }
PS: Feign request timeout problem
The default timeout of Hystrix is 1 second. If there is no response after this time, the fallback code will be entered. The first request is often slow (because of Spring's lazy loading mechanism, which requires instantiating some classes), and the response time may be greater than 1 second.
There are three solutions, taking feign as an example.
Method one
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 5000
This configuration is to change the timeout of Hystrix to 5 seconds
Method two
hystrix.command. default.execution.timeout.enabled: false
This configuration is used to disable the timeout period of Hystrix
Method 3
feign.hystrix.enabled: false
This configuration is used to simply disable feign's hystrix . This approach is not recommended except in some special scenarios.
<br><br>
The above is the detailed content of Feign of spring cloud uses HTTP to request remote services. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

Chirp Down can also be called JJDown. This is a video download tool specially created for Bilibili. However, many friends do not understand this software. Today, let the editor explain to you what Chirp Down is? How to use chirp down. 1. The origin of Chirpdown Chirpdown originated in 2014. It is a very old video downloading software. The interface adopts Win10 tile style, which is simple, beautiful and easy to operate. Chirna is the poster girl of Chirpdown, and the artist is あさひクロイ. Jijidown has always been committed to providing users with the best download experience, constantly updating and optimizing the software, solving various problems and bugs, and adding new functions and features. The function of Chirp Down Chirp Down is
