Spring Cloud中如何优雅的使用Feign调用接口

JAVA 项目中接口调用怎么作 ?

  • Httpclient
  • Okhttp
  • Httpurlconnection
  • RestTemplate

上面是最多见的几种用法,咱们今天要介绍的用法比上面的更简单,方便,它就是 Feigngit

Feign是一个声明式的REST客户端,它的目的就是让REST调用更加简单。github

Feign提供了HTTP请求的模板,经过编写简单的接口和插入注解,就能够定义好HTTP请求的参数、格式、地址等信息。spring

而Feign则会彻底代理HTTP请求,咱们只须要像调用方法同样调用它就能够完成服务请求及相关处理。api

SpringCloud对Feign进行了封装,使其支持SpringMVC标准注解和HttpMessageConverters。app

Feign能够与Eureka和Ribbon组合使用以支持负载均衡。负载均衡


SpringCloud中使用Feign

当咱们搭建好注册中心Eureka以后,就是须要将本身的服务注册到Eureka中,而后别的服务能够直接调用。ide

首先呢是服务提供方须要注册到Eureka中,这边咱们新建一个房产服务fangjia-fsh-house-serviceui

fangjia-fsh-house-service中提供跟房子相关的接口,好比最简单的获取房子的基本信息this

/**
 * 获取房产信息
 * @param houseId 房产编号
 * @return 
 */
 @GetMapping("/{houseId}")
 public ResponseData hosueInfo(@PathVariable("houseId")Long houseId) {
     return ResponseData.ok(houseService.getHouseInfo(houseId));
 }

另外咱们起一个项目来消费房产服务的这个接口,房产置换服务fangjia-fsh-substitution-service编码

/**
 * 获取置换信息
 * @param sid
 * @return
 */
 @GetMapping("/{sid}")
 public ResponseData substitutionInfo(@PathVariable("sid") Long sid) {
     return ResponseData.ok(substitutionService.getSubstitutionInfo(sid));
 }

在substitutionService中须要消费房产服务的获取房产信息接口,通常的作法咱们都会经过Httpclient或者最底层的Httpurlconnection来直接调用接口,固然这些都须要本身集成或者封装,在spring里面已经有了一个很好的封装,那就是RestTemplate来调用接口。

关于RestTemplate的使用能够查看个人这篇文章:http://cxytiandi.com/blog/detail/6157

能够直接注入对象,而后调用接口,这种方式惟一的弊端就是你须要知道服务提供者的地址,根据指定的地址来进行调用

@Autowired
private RestTemplate restTemplate;

@Override
public SubstitutionDto getSubstitutionInfo(Long sid) {
    House house = this.restTemplate.getForObject("http://localhost:8000/hosue/" + id, House.class);
  // .......
}

另外一种就是咱们今天的主角,简单的调用方式就是使用一个声明式的REST客户端Feign来进行接口调用

用了Feign以后调用接口只须要定义相同的接口便可实现调用

使用Feign确定要引入jar的依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

在启动类上加@EnableFeignClients注解,若是你的Feign接口定义跟你的启动类不在一个包名下,还须要制定扫描的包名@EnableFeignClients(basePackages = "com.fangjia.api.client")

这边建议你们将接口的消费定义,单独抽一个项目出来,后面打成公共的jar,这样不管是哪一个项目须要调用接口,引入公共的接口SDK jar便可,不用从新定义一遍了。

**
 * 房生活房产服务API调用客户端
 *
 * @author yinjihuan
 * @create 2017-10-27 13:55
 **/
@FeignClient(value = "fangjia-fsh-house-service", path = "/house", configuration = FeignConfiguration.class, fallback = HouseRemoteClientHystrix.class)
public interface HouseRemoteClient {
    
    /**
     * 获取企业下某用户的有效房产信息
     * @param eid    企业编号
     * @param uid    用户编号
     * @return
     */
    @GetMapping("/list/{eid}/{uid}")
    public HouseListDto hosueList(@PathVariable("eid")Long eid, @PathVariable("uid")String uid);    
    
    /**
     * 获取房产详细信息
     * @param houseId 房产编号
     * @return
     */
    @GetMapping("/{houseId}")
    public HouseInfoDto hosueInfo(@PathVariable("houseId")Long houseId);
    
}

@FeignClient里的value表示你要消费哪一个服务的接口,path就是统一的前缀,也就是咱们HouseController中类上面的@RequestMapping("/house")的地址

@FeignClient里的configuration可让你自定义配置信息来覆盖Feign的默认配置,
好比配置日志输出

日志的输出还须要在配置文件中指定才能生效logging.level.com.fangjia.api.client.fsh.house.HouseRemoteClient=DEBUG

@Configuration
public class FeignConfiguration {
    @Bean  
    Logger.Level feignLoggerLevel() {  
        return Logger.Level.FULL;  
    }  
}

@FeignClient里的fallback可让你的接口在熔断处理时,返回默认的值给调用方,这个通常有2种方式:

  • 实现Feign的接口,实现全部的默认方法
/**
 * 房产服务调用熔断默认返回处理
 *
 * @author yinjihuan
 * @create 2017-10-29 14:30
 **/
@Component
public class HouseRemoteClientHystrix implements HouseRemoteClient {

    @Override
    public HouseListDto hosueList(Long eid, String uid) {
        return new HouseListDto();
    }

    @Override
    public HouseInfoDto hosueInfo(Long houseId) {
        return new HouseInfoDto();
    }
}

另外一种就是@FeignClient里的fallbackFactory,效果是同样的

使用的话更简单了,和普通的Service的类同样使用,注入进来,而后直接调用方法就至关于调用远程接口了

@Autowired
private HouseRemoteClient houseRemoteClient;

HouseInfoDto houseInfoDto = houseRemoteClient.hosueInfo(1L);

普通Java项目中如何使用Feign

经过上面的讲解,在SpringCloud中使用Feign显得那么的天然,由于集成这件事SpringCloud已经帮咱们作好了,这是广大开发人员的福音。

那若是大家没有使用SpringCloud来进行开发,我能用Feign来调用接口马,答案是:固然

首先你须要看一遍文档,若是还不会用你来找我:https://github.com/OpenFeign/feign

咱们看官方的提个Demo:

定义了一个GitHub的接口调用类,上面配置了请求方式以及参数,是经过Feign自带的注解方式配置的

而后经过Feign.builder()构建一个客户端,同时能够设置编码,解码须要用到的类,以及访问的目标地址等等信息,固然也包括日志的设置,输出等等。。

interface GitHub {
  @RequestLine("GET /repos/{owner}/{repo}/contributors")
  List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);
}

static class Contributor {
  String login;
  int contributions;
}

public static void main(String... args) {
  GitHub github = Feign.builder()
                       .decoder(new GsonDecoder())
                       .target(GitHub.class, "https://api.github.com");

  // Fetch and print a list of the contributors to this library.
  List<Contributor> contributors = github.contributors("OpenFeign", "feign");
  for (Contributor contributor : contributors) {
    System.out.println(contributor.login + " (" + contributor.contributions + ")");
  }
}

具体代码能够参考个人github:

https://github.com/yinjihuan/spring-cloud

相关文章
相关标签/搜索