讨论声明式的REST Client Feign7. Declarative REST Client: Feignhttps://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html首先我们来看一下Feign是什么,Feign是一个声明式的web service的客户端,他让写web service的客户端更加的容易,如果你想用Feign创建一个接口,然后添加一些注解,就OK了,他说他支持Feign的注解,JAX-RS的注解,大家知道JAX-RS是什么吗,JAX-RS是JAVA API For RESTFul Service,说到JAX-RS就不得不说到另一个标准,它是一个WEB Service的标准,JAX-WS,JAVA API For Web Service,这个大家可能都看过,就是之前的SOAP协议,WEB Service里面的一堆标准,有了REST出来了,JAVA与时俱进,他又搞了一个REST Service的一个标准,它是一个标准,如果大家想深入了解JAX-RS的话,你用这样的一个框架进行入门,叫jersey,JAX-RS的话,其实有一部分是参考了jersey的设计,当然cxf,他也是支持JAX-RS标准的,Feign同样支持,可插拔的编码器和解码器,Spring Cloud为Feign添加了SpringMVC的注解,使用相同的HttpMessageConverters,我们知道SpringMVC的Converter,说白了Spring Cloud扩展了Feign,支持了SpringMVC的注解,在Spring Cloud使用Feign的时候,他整合了Ribbon和Eureka,以提供负载均衡的能力,首先他是一个声明式的HTTP的client,如果你想使用它的话,创建一个接口,然后添加注解,最后他还整合了Ribbon和Eureka,他还可以使用SpringMVC的注解,降低了我们的学习成本,否则不管我们要学Feign的注解,我们其实都是有额外的学习成本的,我们来看一下Feign的githubFeign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide a load balanced http client when using Feign.https://github.com/OpenFeign/feign它的URL最近发生了变化,其实他是netflix的产品,他被重定向到OpenFeign/feign,我们来看一下Feign的版本,https://github.com/OpenFeign/feign/releases它的版本迭代的非常的快,它的代码更新也是非常的频繁,这个东西很活跃,很有前途的,怎么样使用这个Feign呢,7.1 How to Include Feign光知道这个东西介绍的再好有什么用啊,我们怎么样用,在Spring Cloud或者SpringBoot里面,基本上会有一个思维定式了,引入他的starterTo include Feign in your project use the starter with group org.springframework.cloud and artifact id spring-cloud-starter-openfeign. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.Example spring boot app@SpringBootApplication
@EnableFeignClients
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}我们在启动类上加上@EnableFeignClients这个注解StoreClient.java. @FeignClient("stores")
public interface StoreClient {@RequestMapping(method = RequestMethod.GET, value = "/stores")List<Store> getStores();@RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")Store update(@PathVariable("storeId") Long storeId, Store store);
}这才是正题,创建一个接口,在接口上添加一个注解localhost:8010/movie/1timeout解释一下,可能是应用刚启动,因为它会从Eureka上拉,拉东西,它会把虚拟IP@FeignClient("microservice-simple-provider-user")转成真正的IP,所以他可能会造成一个超时,localhost:8010/test/?id=1&username=zhangsan&age=20{"id":1,"username":"zhangsan","name":null,"age":20,"balance":null}localhost:7900/get-user/?id=1&username=zhangsan&age=20localhost:8010/test-get/?id=1&username=zhangsan&age=20feign.FeignException: status 405 reading UserFeignClient#getUser(User); content:{"timestamp":1566720796075,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/get-user"
}你请求的方法是POST,// 该请求不会成功,只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求。
// 可能是我没找到相应的注解或使用方法错误。
@RequestMapping(value = "/get-user", method = RequestMethod.GET)
public User getUser(User user);
package com.learn.cloud.entity;import java.math.BigDecimal;public class User {public User(Long id, String name) {super();this.id = id;this.name = name;}public User() {super();}private Long id;private String username;private String name;private Short age;private BigDecimal balance;public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getUsername() {return this.username;}public void setUsername(String username) {this.username = username;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public Short getAge() {return this.age;}public void setAge(Short age) {this.age = age;}public BigDecimal getBalance() {return this.balance;}public void setBalance(BigDecimal balance) {this.balance = balance;}
}
package com.learn.cloud.controller;import java.util.ArrayList;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import com.google.common.collect.Lists;
import com.learn.cloud.entity.User;
import com.learn.cloud.mapper.UserMapper;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;@RestController
public class UserController {@Autowiredprivate UserMapper userMapper;@Autowiredprivate EurekaClient eurekaClient;@Autowiredprivate DiscoveryClient discoveryClient;@GetMapping("/simple/{id}")public User findById(@PathVariable Long id) {return this.userMapper.getUserById(id);}@GetMapping("/eureka-instance")public String serviceUrl() {InstanceInfo instance = this.eurekaClient.getNextServerFromEureka("MICROSERVICE-SIMPLE-PROVIDER-USER", false);return instance.getHomePageUrl();}@GetMapping("/instance-info")public ServiceInstance showInfo() {ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();return localServiceInstance;}@PostMapping("/user")public User postUser(@RequestBody User user) {return user;}// 该请求不会成功@GetMapping("/get-user")public User getUser(User user) {return user;}@GetMapping("list-all")public List<User> listAll() {ArrayList<User> list = Lists.newArrayList();User user = new User(1L, "zhangsan");User user2 = new User(2L, "zhangsan");User user3 = new User(3L, "zhangsan");list.add(user);list.add(user2);list.add(user3);return list;}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><artifactId>microservice-consumer-movie-feign</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>microservice-simple-consumer-movie</name><description>Demo project for Spring Boot</description><parent><groupId>cn.learn</groupId><artifactId>microcloud02</artifactId><version>0.0.1</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-feign</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
#debug=true
server.port=8010eureka.client.serviceUrl.defaultZone=http://admin:1234@10.40.8.152:8761/eurekaspring.application.name=microservice-consumer-movie-ribbon
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
eureka.client.healthcheck.enabled=true
spring.redis.host=10.40.8.152
spring.redis.password=1234
spring.redis.port=6379#stores.ribbon.listOfServers=10.40.8.144:7900
package com.learn.cloud.feign;import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;import com.learn.cloud.entity.User;@FeignClient("microservice-simple-provider-user")
public interface UserFeignClient {@RequestMapping(value = "/simple/{id}", method = RequestMethod.GET)// 两个坑:1. @GetMapping不支持   2. @PathVariable得设置valuepublic User findById(@PathVariable("id") Long id); @RequestMapping(value = "/user", method = RequestMethod.POST)public User postUser(@RequestBody User user);// 该请求不会成功,只要参数是复杂对象,即使指定了是GET方法,feign依然会以POST方法进行发送请求。可能是我没找到相应的注解或使用方法错误。@RequestMapping(value = "/get-user", method = RequestMethod.GET)public User getUser(User user);}
package com.learn.cloud.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import com.learn.cloud.entity.User;
import com.learn.cloud.feign.UserFeignClient;@RestController
public class MovieController {@Autowiredprivate UserFeignClient userFeignClient;@GetMapping("/movie/{id}")public User findById(@PathVariable Long id) {return this.userFeignClient.findById(id);}@GetMapping("/test")public User testPost(User user) {return this.userFeignClient.postUser(user);}@GetMapping("/test-get")public User testGet(User user) {return this.userFeignClient.getUser(user);}
}
package com.learn.cloud;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerMovieFeignApplication {public static void main(String[] args) {SpringApplication.run(ConsumerMovieFeignApplication.class, args);}
}

Feign-1 Feign的简介及基础使用相关推荐

  1. DL:深度学习(神经网络)的简介、基础知识(神经元/感知机、训练策略、预测原理)、算法分类、经典案例应用之详细攻略

    DL:深度学习(神经网络)的简介.基础知识(神经元/感知机.训练策略.预测原理).算法分类.经典案例应用之详细攻略 目录 深度学习(神经网络)的简介 1.深度学习浪潮兴起的三大因素 深度学习(神经网络 ...

  2. JavaScript学习笔记01【基础——简介、基础语法、运算符、特殊语法、流程控制语句】

    w3school 在线教程:https://www.w3school.com.cn JavaScript学习笔记01[基础--简介.基础语法.运算符.特殊语法.流程控制语句][day01] JavaS ...

  3. PyTorch学习笔记(二):PyTorch简介与基础知识

    往期学习资料推荐: 1.Pytorch实战笔记_GoAI的博客-CSDN博客 2.Pytorch入门教程_GoAI的博客-CSDN博客 本系列目录: PyTorch学习笔记(一):PyTorch环境安 ...

  4. C#基础编程——简介及基础语法

    C#基础编程--简介及基础语法 百科介绍 C#是微软公司发布的一种由C和C++衍生出来的面向对象的编程语言.运行于.NET Framework和.NET Core(完全开源,跨平台)之上的高级程序设计 ...

  5. 2.JSR简介 - JavaEE基础系列

    JSR, Java Specification Request, Java规范请求; 也有的地方翻译为Java规范提案. 在前面的文章 1. Java EE简介 - JavaEE基础系列中, 简要介绍 ...

  6. Flask学习之旅——2.1 模板简介及基础使用

    Flask学习之旅--2.1 模板简介及基础使用 前言 本文为<知了传课--模板简介>的学习笔记. 原文地址:第一节:模板简介 - Python框架Flask基础教程 - 知了传课 (zl ...

  7. Python|并发编程|爬虫|单线程|多线程|异步I/O|360图片|Selenium及JavaScript|Scrapy框架|BOM 和 DOM 操作简介|语言基础50课:学习(12)

    文章目录 系列目录 原项目地址 第37课:并发编程在爬虫中的应用 单线程版本 多线程版本 异步I/O版本 总结 第38课:抓取网页动态内容 Selenium 介绍 使用Selenium 加载页面 查找 ...

  8. Python学习1——python简介和基础入门

    转载  原文Python学习之路[第一篇]-Python简介和基础入门:https://www.cnblogs.com/linupython/p/5713324.html 1.python3.7.2下 ...

  9. RSA算法原理——(2)RSA简介及基础数论知识

    上期为大家介绍了目前常见加密算法,相信阅读过的同学们对目前的加密算法也算是有了一个大概的了解.如果你对这些解密算法概念及特点还不是很清晰的话,昌昌非常推荐大家可以看看HTTPS的加密通信原理,因为HT ...

最新文章

  1. (干货)微信小程序转发好友
  2. mysql单机多实例启动不了_mysql单机启用多实例的配置方法
  3. java中i+=2什么意思_三分钟看懂Java中i++与++i的性能差别以及循环中如何使用
  4. GCC优化选项:一般的文档里不容易找到的-Os
  5. php工程导致系统蓝屏,经常蓝屏是什么原因
  6. 傲游浏览器怎么更换皮肤 浏览器皮肤更换方法简述
  7. 剑指offer38题
  8. C语言课后习题(32)
  9. 分形:MandelBrot和Julia
  10. 锁机制初探(五)Moniter的实现原理
  11. Contiki学习笔记——Cooja启动失败
  12. EI收录中国期刊目录 各个版本的含义及收录例子-12年初版
  13. ie经常卡死是什么原因_IE6必须死的6个原因
  14. Compose实现webView文件选择
  15. Python3 数据库(MySQL/MongoDB/Redis)
  16. Android部分手机在使用EditText进行自动联想时会先输入拼音的问题
  17. 公众号文章中怎样添加音乐、音频
  18. 西方投资组合理论及其新发展综述
  19. 图像,log处理的一点经验
  20. GB/T28181-2022协议版本标识X-GB-Ver解读

热门文章

  1. Win10 通过升级安装完成后出现了中文字体忽大忽小的问题解决。
  2. 【编程题目】输入一个已经按升序排序过的数组和一个数字,在数组中查找两个数,使得它们的和正好是输入的那个数字。...
  3. HDU 2177HDU 2176
  4. RPA如何助力企业解决人才短缺难题?
  5. Angular中修改第三方组件的样式 - zorro日期选择器右端不对齐的BUG
  6. SQL查询数据并插入新表
  7. Sql 最简单的Sqlserver连接
  8. Linux学习—vim大全
  9. SQL Server 2005无法输入中文的解决方案
  10. gzip,bzip2压缩工具及tar打包工具