[SpringCloud learning] Feign uses interface to call service

Feign: use the interface method to call the service

There are two ways to call microservice access:

1. Microservice name Ribbon

2. Interface and annotation Feigin

When using Ribbon+RestTemplate earlier, a set of templated calling methods were formed by using RestTemplate to encapsulate Http requests. However, in actual development, since there may be more than one call to service dependencies, an interface will often be called There are multiple calls, so usually some client classes are encapsulated for each microservice to wrap the calls of these dependent services. So Feign made further encapsulation on this basis, and used it to help define and implement the definition of dependent service interfaces. Under the implementation of Feign, we only need to create an interface and configure it with annotations to complete the service provision. The interface binding of the party simplifies the development of automatically encapsulating the service calling client when using Spring Cloud Ribbon.

Feign integrates Ribbon

Feign uses Ribbon to maintain service list information, and implements client load balancing through polling. The difference from Ribbon is that Feign only needs to define service interfaces and implement service calls in a declarative way.

After using Feign, instead of using RestTemplate, it is more like using Dubbo+Zookeeper to create an interface and add Reference annotations when the Controller is used. Feign also creates an interface, adds annotations to it to bind the service name and writes the same Controller method as the service provider (no need to write the implementation class), and then enables the function in the startup class.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-9mPTdj6J-1647436586692) (C:\Users\Freeze_three\AppData\Roaming\Typora\typora-user-images\ image-20220316151743609.png)]

Use of Feign

1. As before, neither the service registry Eureka nor the service provider needs to modify any code, and uses the Feign method to implement consumer service calls. In order not to confuse with Ribbon, create a new Module (springcloud-consumer-dept-feign) for comparison, and copy the previous consumer code and configuration.

2. Import pom.xml dependencies, similar to the previous service consumers, with an additional Feign dependency

        <!--Feign-->
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
       

3. Add an interface DeptClientService. Although the Service layer in the name is like the Service layer I learned before, I think it means more Service. Service corresponds to the service of the service provider (the Controller method interface given).

Adding the annotation @FeignClient name on the interface is the service name of the service provider (the service name defined in the yml configuration file), and the url on the method is the same as the url of the controller layer of the service provider.

@Component
@FeignClient(name = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {
    
    

    @GetMapping("/dept/get/{id}")//跟服务提供者的controller的 url相同
    public Dept queryById(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryAll();

    @RequestMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept);

}

4. Modify and copy the Controller from the original consumer. The Ribbon uses the RestTemplate to remotely call the service, and write the address through the service name to call. After using Feign, it simplifies the amount of code we write in Controller, and it is more in line with our habit of calling layer by layer.

package com.freeze.springcloud.controller;

import com.freeze.springcloud.pojo.Dept;
import com.freeze.springcloud.service.DeptClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class DeptConsumerController {
    
    

    @Autowired
    private DeptClientService deptClientService=null;

    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
    
    
        return this.deptClientService.addDept(dept);
    }

    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
    
    
        return this.deptClientService.queryById(id);
    }

    @RequestMapping("/consumer/dept/list")
    public List<Dept> list(){
    
    
        return this.deptClientService.queryAll();
    }
}

Compared with the previous Ribbon+RestTemplate, after using feign, we call other services registered by eureka, which is as simple as calling each service in the code.

I had morning class today, and I only learned one Feign in the afternoon. Due to various dependency versions, it has been unsuccessfully started (the created Service, the reason for the error report is that it cannot be injected, and there is an error report that the Ribbon dependency has not been added, but the new version Eureka includes Ribbon, I’m speechless), in line with the use of all new version dependencies, I finally had no choice but to compromise, went to study video reviews and took someone else’s version, after modifying all dependent versions, IDEA couldn’t respond for a while? ? ! Every time IDEA is restarted, the pom of a module becomes popular, but the back is not red, and the Maven window is still red, but it can be used, and it has been tossing for a long time. . Fortunately, nothing happened.

Guess you like

Origin blog.csdn.net/adminguojieBin/article/details/123536693