Feign使用方法

Feign

Feign 和 OpenFeign 的关系

Feign 最早是由 Netflix 公司进行维护的,后来 Netflix 不再对其进行维护,最终 Feign 由社区进行维护,更名为 OpenFeign。

Feign是 SpringCloud组件中的一个轻量级 Restful的 HTTP 服务客户端,Feign 内置了 Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign 的使用方式是:使用 Feign 的注解定义接口,调用这个接口,就可以调用服务注册中心的服务.

OpenFeign 是 SpringCloud 在 Feign的基础上支持了 SpringMVC 的注解,如 @RequestMapping 等等。OpenFeign 的 @FeignClient 可以解析 SpringMVC 的 @RequestMapping 注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。

使用案例

在线教育网站的项目为例,order服务远程调用ucenter服务

image-20220923115756833

第一步:order服务需要定义一个 OpenFeign 接口

@FeignClient("service-ucenter")
@Component
public interface UcenterClient {

    //根据用户id获取用户信息
    @PostMapping("/ucenter/member/getInfoUc/{id}")
    public Member getInfo(@PathVariable String id);

}

接口上添加了注解@FeignClient,而且括号里面指定了服务名:service-ucenter。显示声明这个接口用来远程调用 service-ucenter服务。@PostMapping表明ucenter服务中要有一个对应的方法,方法路径和 order 服务中的接口 URL 地址一致。

第二步:order 启动类上添加 @EnableFeignClients注解开启远程调用服务,且需要开启服务发现。

@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.wang"})
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }
}

第三步:order 服务的 POM 文件中引入 OpenFeign 组件。

<!--服务调用-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

第四步:引入 UcenterClient ,order 服务远程调用 ucenter 服务即可。

@Autowired
private UcenterClient ucenterClient;

ucenterClient.getInfo(id);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值