在Spring boot编写的REST接口中,也许会用到:访问其它接口的功能。除了springboot自带的httpclient类外,这里提供一个新的方法:feign。
-
添加对feign的支持
在pom.xml中添加引用<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
注: 在springboot 1.8版本以上中使用fegin时,除了添加fegin的链接外,还需要添加以下依赖 ,具体见
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Finchley.M8</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
-
编写接口
在自己接口定义中,接口名称上使用@FeignClient(name="自定义",url="外部提供的接口访问地址")
;在接口方法中使用@RequestMapping(value="具体访问路径"[,method="POST\GET"\)
例子:@FeignClient(name = "appService", url = "http://XXXX:port") public interface AppService { @RequestMapping(value = "/userLogin", method = RequestMethod.POST) JSONObject login(@RequestBody User user); }
-
开启Feign
在启动类中使用@EnableFeignClients
开启Feign的支持