spring cloud 2.0 入门系列一 (3)声明式http客户端-Feign

Spring Cloud Feign

Feign是一个声明性的Web服务客户端。它使编写Web服务客户端变得更容易。feign已经集成了Ribbon客户端负载功能,所以使用feign时可无需考虑客户端的负载。

服务说明及API

请参考官网:http://cloud.spring.io/spring-cloud-openfeign/single/spring-cloud-openfeign.html

应用说明

使用框架

  • SpringBoot 2.0.3
  • SpringCloud Finchley.RELEASE

环境搭建

pom文件修改

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 系统注册与监测服务 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- 系统配置管理中心 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<!-- spring 配置读取(@ConfigurationProperties(prefix = "test")) -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

<!-- feign 声明式服务调用框架 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- feign httpclient,提高http性能 -->
<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-httpclient</artifactId>
</dependency>

启动文件修改

在SpringBoot的启动类上添加注释:@EnableDiscoveryClient@EnableFeignClients

配置文件修改

在需要使用feign功能的应用配置文件中添加配置:

feign:
  httpclient:
    enabled: true

编写调用服务的接口

//首先使用serverId查找服务,如果找不到再使用url查找。
@FeignClient(value = "server-user", url = "http://localhost:8781")
public interface ExternalPersonService {

    /**
     * 查询组织架构用户
     *
     * @param searchColumn 查询的字段
     * @param searchValue  查询的数据
     * @return
     */
    @RequestMapping(value = "/person/findPerson", method = RequestMethod.GET)
    public Person findPerson(@RequestParam("searchColumn") String searchColumn,
                             @RequestParam("searchValue") String searchValue);

}

使用feign声明式HTTP客户端,调用微服务接口非常简单,只需要按照接口要求定义好需要调用的接口(类似于写一个controller类),在类上使用@FeignClient声明接口为feign服务接口即可实现服务调用。

代码样例

feign:https://gitee.com/xiaoxming/cloud_project/tree/master/app-console-web
接口提供:https://gitee.com/xiaoxming/cloud_project/tree/master/server-user

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值