Microservices-Basic use of OpenFeign

I. Introduction

2. Basic use of OpenFeign

1. Introduction to OpenFeign

OpenFeign is a declarative, templated HTTP client that makes it easy to call RESTful web services. Using OpenFeign in Spring Cloud, you can use HTTP requests to access remote services like calling local methods, and developers do not need to pay attention to the details of remote HTTP requests.

OpenFeign's Spring application architecture is generally divided into three parts, namely the registration center, service provider and service consumer. The service provider registers itself with the service registry, and then when the service consumer sends a request through OpenFeign, OpenFeign will obtain information about the service provider from the service registry, and then send a network request to the service provider.

Using OpenFeign, you only need to create an interface and add annotations to implement remote service calls. It simplifies the RestTemplate code, implements Ribbon load balancing, and makes the code more concise. OpenFeign supports Spring MVC annotations, such as @RequestMapping, @PathVariable, etc., which makes it more convenient to integrate with Spring Cloud.

2、Feign和OpenFeign

The difference between Feign and OpenFeign is that Feign is a part of Spring Cloud, while OpenFeign is an encapsulation of Feign, providing more functions and better integration. OpenFeign not only supports Spring MVC annotations, but also supports JAX-RS annotations and JPA annotations. In addition, OpenFeign also supports custom annotations and encoders, making it better able to meet different needs.

The predecessor of the OpenFeign component is the Netflix Feign project. It was first developed by Netflix as part of the Netflix OSS project. Later, the Feign project was contributed to open source organizations, and thus the Spring Cloud OpenFeign component we use today came into being.

Feign and OpenFeign have many similarities, except that OpenFeign supports MVC annotations.

OpenFeign can be considered an enhanced version of Feign.

A brief summary of what OpenFeign can be used for:

OpenFeign is a declarative HTTP client that makes remote calls easier.
Provides an HTTP request template, writes a simple interface and inserts annotations, and then you can define the parameters, format, address and other information of the HTTP request.
Integrate Ribbon (load balancing component) and Hystix (service fuse component), no need to display and use this Two components,
Spring Cloud Feign, extend support for SpringMVC annotations based on Netflix Feign.

3. OpenFegin communication optimization

3.1 Introduction to GZIP

(1) Introduction to gzip: gzip is a data format that uses the deflate algorithm to compress data; gzip is a popular data compression algorithm that is widely used, especially on the Linux platform.

(2) Gzip capability: When Gzip compresses to a plain text data, the effect is very obvious, and the data size can be reduced by more than 70%.

(3) The function of gzip: After the network data is compressed, the number of bytes transmitted by the network is actually reduced. The most obvious benefit is that it can speed up the loading of web pages. The benefits of faster web page loading are self-evident. In addition to saving traffic and improving users' browsing experience, another potential benefit is that Gzip has a better relationship with search engine crawlers. Google, for example, can crawl web pages faster than ordinary manual crawling by reading gzip files directly.

3.2. Regulations on compressed transmission in the HTTP protocol (principle)

Insert image description here
First: The client's request header to the server contains: Accept-Encoding:gzip, deflate fields, indicating to the server the compression format (gzip or deflate) supported by the client. If this message header is not sent, the server will not compress it. of.

Second: After receiving the request, if the server finds that the request header contains the Accept-Encoding field and supports this type of compression, it will compress the response message and return it to the client, and carry the Content-Encoding: gzip message header , indicating that the response message is compressed according to this format.

Third: After receiving the response, the client first determines whether there is a Content-Encoding header, and if so, decompresses the message in this format. Otherwise, the message will be processed as normal.

3.3. Apply GZIP compression in OpenFeign technology

In the Spring Cloud microservice system, the complete process of a request is as follows:
Insert image description here
In the overall process, if GZIP compression is used to transmit data, two requests-responses are involved. The connection point of these two requests-responses is the Application Client, so we need to configure and enable GZIP compression in the Application Client to realize compressed data transmission.

3.4. Configure only OpenFeign request-response GZIP compression

When the amount of interactive data is not enough, the compressed content cannot be seen.

Here only GZIP is enabled in the Feign request-response process, that is, GZIP compression is not enabled in the request response between the browser and the Application Client.

In the global configuration file, use the following configuration to implement GZIP compression of OpenFeign request-response
Insert image description here

4. OpenFegin example

Module description:
The user module calls the interface of the product module

4.1. Dependency preparation

<!--nacos-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!--openfegin-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

4.2. Add EnableFeginClients to the startup class

Only by adding the @EnableFeignClients annotation to the startup class can the fegin interface be recognized by the class marked with @FeginClient.

@EnableSwagger2
@SpringBootApplication
@EnableDiscoveryClient
@Slf4j
@EnableFeignClients
public class UserApplication {
    
    
    public static void main(String[] args) throws UnknownHostException {
    
    
        ConfigurableApplicationContext application = SpringApplication.run(UserApplication.class, args);

        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        // 未配置默认空白
        if (path == null) {
    
    
            path = "";
        }
        // 未配置默认空白
        if (port == null) {
    
    
            port = "8080";
        }
        log.info("\n----------------------------------------------------------\n\t" +
                "项目启动成功,访问路径如下:\n\t" +
                "本地路径: http://localhost:" + port + path + "/\n\t" +
                "网络地址: http://" + ip + ":" + port + path + "/\n\t" +
                "接口地址: http://" + ip + ":" + port + path + "/swagger-ui.html\n\t"  +
                "API文档: http://" + ip + ":" + port + path + "/doc.html\n" +
                "----------------------------------------------------------");
    }
}

4.3. Write fegin interface

注意:The value passed in @FeignClient is the service name registered by the product module on nacos.
Insert image description here

@FeignClient(value = "product-demo",path = "")
@Service
public interface ProductService {
    
    
    @RequestMapping(value = "/test/hello",method = RequestMethod.GET)
    String hello();
}

4.4. Call fegin interface

@RestController
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private ProductService productService;

    @GetMapping("/test")
    public String test(){
    
    
        return productService.hello();
    }
}

Insert image description here

3. Summary

Using OpenFeign makes it easier for you to write HTTP client code without having to manually handle the underlying HTTP requests and responses.

If this blog is of some help to you, please remember to leave a message + like + favorite.

Guess you like

Origin blog.csdn.net/wmj20001225/article/details/132670611