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请求 }</springuser>
@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);*/}</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!

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.


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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
