Feign 开源地址:
1.编写接口服务
(1)导入jar包
org.springframework.boot spring-boot-starter-parent 2.0.2.RELEASE org.springframework.boot spring-boot-starter-web
(2)编写接口
public class Person { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; }}
@RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "hello world"; } @RequestMapping(value = "/person/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public Person person(@PathVariable Integer id) { Person person = new Person(); person.setAge(18); person.setId(id); person.setName("aa"); return person; }
2.Feign客户端 (此处通过cxf做一个对比)
(1)cxf客户端
org.apache.cxf cxf-core 3.1.10 org.apache.cxf cxf-rt-rs-client 3.1.10
public class CxfClient { public static void main(String[] args) throws Exception{ //创建WebClient WebClient client = WebClient.create("http://localhost:8080/hello"); //获取响应 Response response = client.get(); //获取响应内容 InputStream inputStream = (InputStream) response.getEntity(); String content = IOUtils.readStringFromStream(inputStream); //输出结果 System.out.println("返回结果为:" + content); }}
(2)feign客户端
io.github.openfeign feign-core 9.5.0 io.github.openfeign feign-gson 9.5.0
import com.idelan.cloud.model.Person;import feign.Param;import feign.RequestLine;/** * Created with IDEA * User gyli * date 2018/12/6 */public interface ClientInterface { @RequestLine("GET /hello") public String hello(); @RequestLine("GET /person/{id}") public Person getPerson(@Param("id") Integer id);}
public static void main(String[] args) { ClientInterface helloClient = Feign.builder().target(ClientInterface.class, "http://localhost:8080"); String hello = helloClient.hello(); System.out.println(hello); ClientInterface clientInterface = Feign.builder() .decoder(new GsonDecoder()) .target(ClientInterface.class, "http://localhost:8080"); Person person = clientInterface.getPerson(2); System.out.println(person.getId()); System.out.println(person.getName()); System.out.println(person.getAge()); }