Spring Cloud-使用feign来消费Restful服务

来源:互联网 发布:win10拆卸软件 编辑:程序博客网 时间:2024/05/20 10:55

PS:本文以阿里云验证车牌接口为例,以实现为主

feign简介

  Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求,这整个调用过程和Dubbo的RPC非常类似。开发起来非常的优雅。

1. 添加依赖

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

2. 开启Feign支持

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

3. 接口编写,并实现Feign client

import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.*;@FeignClient(url = "http://jisucphjy.market.alicloudapi.com", name = "demo-service")public interface DemoService {    @RequestMapping(method = RequestMethod.GET,value = "/licenseplate/verify",consumes = MediaType.APPLICATION_JSON_VALUE)    @ResponseBody    Response validatedVehicle(@RequestHeader("Authorization") String authorization,                               @RequestParam("engineno") String engineno,                               @RequestParam("lsnum") String lsnum,                               @RequestParam("lsprefix") String lsprefix,                               @RequestParam("lstype") String lstype);}

@FeignClient中url属性指定Restful接口资源路径; name属性指定当前Bean;
@FeignClient中url和@RequestMapping中value为完整的接口路径;consumes属性指定请求方式为json;
@RequestHeader(“Authorization”)设置Request Header中Authorization属性;
@RequestParam设置请求参数,本例中请求方式为GET方式,feign的模块化特性会将@RequestParam标记的参数以key=value&key=value格式拼接到url中;

服务注入

// 注入服务提供者,远程的Http服务@Autowiredprivate DemoService demoService;

接口调用

Response response = vehicleService.validatedVehicle(CodeType.APPCODE, vin,lsnum,lsprefix,lstype);
阅读全文
0 0