微服务学习6——采用Feign进行通信

本文介绍如何在Spring Cloud项目中集成Feign声明式REST客户端,包括Maven依赖配置、启动类注解及Feign接口定义。通过示例演示如何创建负载均衡的HTTP客户端,实现对远程服务的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这些东东的细节都可以看原版文档

1,maven设置:

To include Feign in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-openfeign. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

 

也就是这么设置:

<dependency>

<groupId>org.springframework.cloud </groupId>

<artifactId>spring-cloud-starter-openfeign</artifactId>

</dependency>

 

2,入口类设置

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

 

3,使用Feign类

@FeignClient("stores") public interface StoreClient { @RequestMapping(method = RequestMethod.GET, value = "/stores") List<Store> getStores(); @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") Store update(@PathVariable("storeId") Long storeId, Store store); }

 

In the @FeignClient annotation the String value ("stores" above) is an arbitrary client name, which is used to create a Ribbon load balancer (see below for details of Ribbon support). You can also specify a URL using the url attribute (absolute value or just a hostname). The name of the bean in the application context is the fully qualified name of the interface. To specify your own alias value you can use the qualifier value of the @FeignClient annotation.

The Ribbon client above will want to discover the physical addresses for the "stores" service. If your application is a Eureka client then it will resolve the service in the Eureka service registry. If you don’t want to use Eureka, you can simply configure a list of servers in your external configuration (see above for example).

 

大意就是:

@FeignClient后面的"stores"是任意取的,是用来创建Ribbon load balancer,实际上就是要调用的服务,比如这一句:

@FeignClient(name = "product")

这个product对应的是服务名称:

 

 

Feign是一个声明式REST客户端(伪RPC)

采用了基于接口的注解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值