feign 远程调用详解

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

1:引入依赖

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

2:定义服务地址

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

3:启动类添加 @EnableFeignClients 注解

java 复制代码
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:定义服务端接口

java 复制代码
@RequiredArgsConstructor
@RestController
@RequestMapping("/test")
public class TestController {

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

}

5:创建 feign 客户端接口

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

    /**
     * 查询信息

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

}

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

java 复制代码
@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 可以实现客户端负载均衡。

相关推荐
洛阳纸贵17 天前
基于SpringCloud的广告系统设计与实现(四)
java·spring·spring cloud·feign·服务调用·索引、
微扬嘴角1 个月前
springcloud篇2-feign、gateway
gateway·springcloud·feign
解梦者2 个月前
Spring(七)Spring Cloud----Feign、Zuul和Apollo
spring·spring cloud·feign·apollo·zuul
uncleqiao2 个月前
10.请求拦截和响应拦截
java·feign
uncleqiao2 个月前
3.4.SynchronousMethodHandler组件之ResponseHandler
java·feign
uncleqiao2 个月前
5.Feign与ReflectiveFeign
java·feign
珍珠是蚌的眼泪5 个月前
微服务_入门2
网关·微服务·gateway·远程调用·feign
一叶飘零_sweeeet5 个月前
为什么 Feign 要用 HTTP 而不是 RPC?
java·网络协议·http·spring cloud·rpc·feign
Xiu Yan5 个月前
负载均衡 Ribbon 与 Fegin 远程调用原理
运维·spring cloud·ribbon·负载均衡·feign