Feign
一: REST客户端
在spring cloud集群中,各个角色的通信是基于REST服务。因此在调用服务时,就不可避免地需要使用REST服务的请求客户端。 本节介绍另一种REST服务:Feign
REST客户端和浏览器作用有基本相同,但不能理解为浏览器,REST客户端没有界面。而浏览器需要界面。
1.1 REST客户端
首先介绍两种Web Service框架 Apache CXF和Restlet
1.1.1 CXF
是目前一个较为流行的Web Service框架,是Apache下的一个开源项目
public class MyCxfClient {
public static void main(String[] args) throws IOException {
//创建WebClient
WebClient webClient=WebClient.create("http://localhost:8080/person/1");
//获取响应
Response response=webClient.get();
//获取响应内容
InputStream inputStream=(InputStream) response.getEntity();
String contStr=IOUtils.readStringFromStream(inputStream);
//输出字符串
System.out.println(contStr);
}
1.1.2 Restlet
public class MyRestletClient {
public static void main(String[] args) throws Exception {
ClientResource clientResource = new ClientResource(
"http://localhost:8080/person/1");
// 调用GET方法,服务端发布的是GET
Representation representation = clientResource
.get(MediaType.APPLICATION_JSON);
// 创建JacksonRepresentation实例,将响应转化为Map
JacksonRepresentation jacksonRepresentation = new JacksonRepresentation(
representation, HashMap.class);
// 获取转化后的Map对象
Map map = (HashMap) jacksonRepresentation.getObject();
// 输出结果
System.out.println(map.get("id") + "--" + map.get("name") + "--"
+ map.get("age"));
}
二: Feign框架介绍
- Feign是Github上的开源项目,目的是简化Web Service客户端的开发,在使用时,可以使用注解来修饰接口,被修饰的接口具有访问Web Service的能力。
- *初次之外,Feign还支持插件式的编码器和解码器,使用者可以通过该特性对请求和响应进行不同的封装与解析。
- Spring cloud 将Feign集成到Netflix项目中,当与Eureka、Ribbon集成时,Feign就具备了负载均衡的能力
- 利用的自身的注解@RequestLine(“GET /hello”)
2.1 Get
public interface HelloClient {
/**
* 使用了@RequestLine注解
* 表示用GET方法,向"/hello"发送请求
*/
@RequestLine("GET /hello")
String sayHello();
}
-------------------------------------------------------------------------------------------
public static void main(String[] args) {
// 调用Hello接口
HelloClient helloClient = Feign.builder().target(HelloClient.class,
"http://localhost:8080/");
System.out.println(helloClient.sayHello());
}
2.2 传入参数
访问另外一个地址”/person/{personId}”,需要传入参数并且返回JSON字符串
public interface PersonClient {
@RequestLine("GET /person/{personId}")
Person findPerson(@Param("personId") Integer personId);
class Person {
Integer id;
String name;
Integer age;
//省略setter、getter
}
-------------------------------------
public static void main(String[] args) {
PersonClient personClient = Feign.builder().