Bootstrap

feign 远程调用详解

        在平常的开发工作中,我们经常需要跟其他系统交互,比如调用用户系统的用户信息接口、调用支付系统的支付接口等。那么,我们应该通过什么方式进行系统之间的交互呢?今天,简单来总结下 feign 的用法。

     1:引入依赖

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
     <version>版本根据自己业务需要选择</version>
</dependency>

      2:定义服务地址

# 服务名
mall:
  # 服务地址,如果有项目名称或者前置统一的url,建议配置在这儿
  url: http://localhost:8080  
  # 用户名 可选
  account: 
  # 密码 可选
  password: 

     3:启动类添加  @EnableFeignClients 注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
// 启用 Spring Cloud OpenFeign 客户端功能
@EnableFeignClients
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

      4:定义服务端接口

@RequiredArgsConstructor
@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * 查询信息
     */
    @GetMapping(value = "/info")
    public String getTestInfo() {
       return "666";
    }

}

      5:创建 feign 客户端接口

/**
 * 定义feign客户端接口
 */
@FeignClient(name = "mallFeignClient", url = "${mall.url}")
public interface MallFeignClient {

    /**
     * 查询信息

     * @return 信息
     */
    @GetMapping("/test/info")
    String queryTestInfo();

}

      6:使用 feign 调用远程 mall 服务接口

@RestController
@RequestMapping("/test")
@RequiredArgsConstructor
@Slf4j
public class TestController {

    // fegin定义的接口客户端
    private final MallFeignClient mall;

    /**
     * 客户端controller
     *
     * @return 信息
     */
    @GetMapping("/msg")
    public String queryInfo() {
        return mall.queryTestInfo();
    }

}

     7:测试

        调用当前服务 /test/msg 接口,返回 mall 服务 /test/info 接口的返回值

        ​​​​​​ 

        以上为 feign 调用的基本过程,客户端根据服务地址和接口信息调用服务端的接口。feign 是声明式编程,类似于本地方法调用,极大简化系统之间调用的步骤,便于开发和维护。结合 Ribbon 等负载均衡组件,Feign 可以实现客户端负载均衡。

;