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://github.com/xiaoming302/cloud_project/tree/master/app-console-web
接口提供:https://github.com/xiaoming302/cloud_project/tree/master/server-user

猜你喜欢

转载自blog.csdn.net/xiaoluo033/article/details/80946965