Spring Cloud Alibaba OpenFeign

OpenFeig is a declarative REST client. OpenFeig generates a dynamic implementation of the interface (pseudo client) by using JAX-RS or SpringMVC annotations modification methods.

OpenFeig is used by consumers to call providers, so OpenFeig only involves consumers.

OpenFeign has a load balancing function, which can consume and access specified microservices in a load balancing manner.

1. Provider

Create a module. Some interfaces in this module may be called by other modules, so it is called a provider. (Note: This module will be called module A below)

1.1 Introducing dependencies

OpenFeign must be used in conjunction with the Nacos service registry component, so the service registry dependency (nacos-discovery) must be added to the provider’s dependencies.

Because OpenFeig only involves consumers, there is no need to add OpenFeig dependencies in providers.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.6</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>2022.0.0.0-RC2</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

1.2 Configuration File

server:
  port: 8090
spring:
  application:
    name: service-ssm #Microservice name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos

1.3 Writing entity classes

Create an entity class for simulation use.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}

1.4 Writing control layer code

In the controller layer, for convenience, the business layer code and persistence layer code are not written here. Instead, an allUser method is written to simulate the call.

@RequestMapping("/ssm")
@RestController
public class UserController {

    //@Resource
    //private UserService userService;

    @GetMapping("/selectAllUser")
    public List<User> selectAllUser() {
        // List<User> userList = userService.allUser();
        List<User> userList = allUser();
        return userList;
    }

    // Simulate data query
    public static List<User> allUser() {
        ArrayList<User> userList = new ArrayList<>();
        userList.add(new User(001, "Xiao Ming"));
        userList.add(new User(002, "小红"));
        userList.add(new User(003, "Xiao Zhang"));
        userList.add(new User(004, "小王"));
        return userList;
    }
}

2. Consumer

Create another module. This module wants to call certain methods in module A. You can use OpenFeign to generate a dynamic implementation of the interface, and then you can call the interface in module A.

2.1 Introducing dependencies

OpenFeign must be used in conjunction with the Nacos service registry component, so the service registry dependency (nacos-discovery) must be added to the provider’s dependencies.

Because OpenFeig only involves consumers, you need to add OpenFeig dependencies to consumers.

Starting from Spring Cloud 2021.x, OpenFeign uses Spring Cloud Loadbalancer developed by Spring Cloud as the load balancer, so the loadbalancer dependency must be introduced.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.0.6</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- openfeign dependency -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>4.0.0</version>
    </dependency>
    <!-- loadbalancer dependency -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        <version>4.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

2.2 Configuration File

server:
  port: 8080
spring:
  application:
    name: service-openfeign #Microservice name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos

2.3 Writing entity classes

Because the User entity class will be used next, an error will be reported if it is not created, so it is necessary to create an entity class that is the same as the provider. If in your own business, the interface return value and parameters do not involve entity classes, you do not need to create them.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
}

2.4 Define Feign interface

The interface name of Feign can be any name, and the method name in the interface can also be any name. However, the provider service name specified by the @FeignClient parameter cannot be modified. The parameters in @XxxMapping added on interfaces and methods It is cannot be modified and must be the same as the provider’s corresponding request URI.

In a nutshell, copy the provider controller you want to call, and then remove the method body. (Note that the path must be complete)

@FeignClient("service-ssm")
public interface UserService {
    @GetMapping("/ssm/selectAllUser")
    public List<User> selectAllUser();
}

2.5 Writing control layer code

Use the Feign interface in the processor to call the interface of other modules.

@RequestMapping("/openfeign")
@RestController
public class UserController {
    @Resource
    private UserService userService;

    @GetMapping("/selectAllUser")
    public List<User> selectAllUser() {
        HashMap<String, Object> hashMap = new HashMap<>();

        List<User> userList = userService.selectAllUser();
        hashMap.put("userList", userList);
        hashMap.put("message", "This is the consumer module, OpenFeign!!!");

        return hashMap;
    }
}

2.6 Writing startup class

Add the @EnableFeignClients annotation on the startup class.

@EnableFeignClients
@SpringBootApplication
public class SentinelApplication {
    public static void main(String[] args) {
        SpringApplication.run(SentinelApplication.class, args);
    }
}

3. Test

Start the entity classes of the two modules, and you can see the microservice names of the two modules in the service list of the Nacos console.

There is no problem in accessing the provider’s controller in Postman, that is, accessing its own methods in module A.

To access the consumer’s controller in Postman, that is, to call the method in module A in module B, OpenFeign plays a role.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139437 people are learning the system