OpenFeign之第一个Feign程序(十)

Feign简介

Feign是一个Java到HTTP客户端绑定器,它的灵感来自于Retrofit,JAXRS-2.0和WebSocket。Feign的主要目的是将绑定命名的复杂性降低到HTTP api不去考虑rest的复杂性。

Feign使用像Jersey和CXF这样的工具来编写Rest或SOAP服务的java客户端。此外,Feign允许您在诸如Apache HC这样的http库之上编写自己的代码。Feign将你的代码与http API连接起来,通过可定制的解码器和错误处理来将代码与http API连接起来,这些代码可以被写入任何基于文本的http API。

Feign的工作是将注释处理成一个临时的请求。在输出之前,参数以一种简单的方式应用于这些模板。尽管Feign仅限于支持基于文本的api,但它极大地简化了系统方面,比如重新播放请求。此外,Feign可以很容易地对你的转换进行单元测试。

更多讯息可以到feign的GitHub专栏查看。

创建一个简单的Feign程序

首先还是要从我们Spring Cloud服务管理框架Eureka简单示例(三)这篇文章底部拿到源代码,分别运行三个项目的**App类里面的main方法,看看是否能够正常运行,访问:http://localhost:8080/search/1,如果可以看到返回了Person类的id和name属性键值对,说明项目正常运行。

为了测试Feign访问简单的接口,我们在eureka-provider项目的ProviderController控制器的内部添加一个返回简单字符串的方法:

@RequestMapping(value = "/hello", method = RequestMethod.GET, 
		produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String hello(){
	return "hello world!";
}

然后重启eureka-provider项目,访问:http://localhost:8080/hello,浏览器可以返回简单字符串

创建一个新的简单java的maven项目feign-consumer,在pom.xml中引入feign的核心包:

<dependency>
	<groupId>io.github.openfeign</groupId>
	<artifactId>feign-core</artifactId>
	<version>9.7.0</version>
</dependency>
这里有可能openFeign在GitHub上提供的版本不是最新的,或者有其他出入的地方,我们可以去 openFeign的maven仓库 获取这些依赖。

之后参照示例,我们先创建一个PersonClient的interface接口,并使用@RequestLine注解修饰我们的接口:

package com.init.springCloud;

import feign.RequestLine;

public interface PersonClient {

	@RequestLine("GET /hello")
	String toHello();
	
}

接着创建FeignTest类,测试用feign去访问eureka-provider提供的hello方法:

package com.init.springCloud;

import feign.Feign;

public class FeignTest {

	public static void main(String[] args) {
		//1.简单字符串返回值
		PersonClient client1 = Feign.builder()
				.target(PersonClient.class, "http://localhost:8080");
		String result = client1.toHello();
		System.out.println(result);
	}
	
}

运行main方法,可以看到feign已经去调用了我们的hello方法

为了能够看到feign去掉用返回实体的方法,我们在PersonClient接口中新添加一个接口:

@RequestLine("GET /search/{id}")
Person getPersonById(@Param("id") Integer id);
当然,为了返回实体类,也为了不和原来的方法耦合,我们新建一个Person类,
package com.init.springCloud;

import lombok.Data;

@Data
public class Person {

	private Integer id;			//主键ID
	private String name;		//姓名
	
}

这里使用了lombok,需要在pom.xml中添加依赖:

<!-- lombok代码模板解决方案 -->
<dependency>  
     <groupId>org.projectlombok</groupId>  
     <artifactId>lombok</artifactId>  
     <version>1.16.10</version>
</dependency>

同时,为了能够得到实体Person类,还需要用到Feign提供的一个Gson解码器,在pom.xml中引入依赖:

<dependency>
	<groupId>io.github.openfeign</groupId>
	<artifactId>feign-gson</artifactId>
	<version>9.7.0</version>
</dependency>

最后,在FeignTest中的main方法内编写测试代码:

//2.返回一个对象
PersonClient client2 = Feign.builder().decoder(new GsonDecoder())
		.target(PersonClient.class, "http://localhost:8080");
Person person = client2.getPersonById(1);
System.out.println(person);

运行main方法,看到控制台输出了Person类的信息:


到这里,我们也完成了feign的第一个程序

源码点击这里

猜你喜欢

转载自blog.csdn.net/MrSpirit/article/details/80325580
今日推荐