SpringCloud系列教材 (八)- 视图微服务-Feign
步骤1:Feign 概念
步骤2:先运行,看到效果,再学习
步骤3:模仿和排错
步骤4:创建子项目
步骤5:pom.xml
步骤6:实体类
步骤7:Feign 客户端
步骤8:服务类
步骤9:控制器
步骤10:products.html
步骤11:启动类
步骤12:application.yml
步骤13:启动并访问
步骤14:调用图
步骤15:ribbon 和 feign
步骤 1 : Feign 概念
Feign 是什么呢? Feign 是对 Ribbon的封装,使用注解的方式,调用起来更简单。。。 也是主流的方式~
一下就是代码片段的区别
|
|
步骤 2 : 先运行,看到效果,再学习
老规矩,先下载下载区(点击进入)的可运行项目,配置运行起来,确认可用之后,再学习做了哪些步骤以达到这样的效果。
1. 先启动 EurekaServerApplication
2. 然后启动两次 ProductDataServiceApplication, 分别输入 8001和8002.
3. 接着运行 ProductViewServiceFeignApplication以启动 微服务,然后访问地址:
http://127.0.0.1:8012/products
多刷新几遍,会发现这个端口有时候是 8001,有时候是8002. 从而观察到访问 数据服务集群,客户端负载均衡的效果。
步骤 3 : 模仿和排错
在确保可运行项目能够正确无误地运行之后,再严格照着教程的步骤,对代码模仿一遍。
模仿过程难免代码有出入,导致无法得到期望的运行结果,此时此刻通过比较正确答案 ( 可运行项目 ) 和自己的代码,来定位问题所在。
采用这种方式,学习有效果,排错有效率,可以较为明显地提升学习速度,跨过学习路上的各个槛。
推荐使用diffmerge软件,进行文件夹比较。把你自己做的项目文件夹,和我的可运行项目文件夹进行比较。
这个软件很牛逼的,可以知道文件夹里哪两个文件不对,并且很明显地标记出来
这里提供了绿色安装和使用教程:diffmerge 下载和使用教程
步骤 4 : 创建子项目
创建子项目 product-view-service-feign
步骤 5 : pom.xml
jar 包多了个 spring-cloud-starter-openfeign,就是用来支持 Feign 方式的。
|
步骤 6 : 实体类
|
步骤 7 : Feign 客户端
Feign 客户端, 通过 注解方式 访问 访问PRODUCT-DATA-SERVICE服务的 products路径, product-data-service 既不是域名也不是ip地址,而是 数据服务在 eureka 注册中心的名称。
注意看,这里只是指定了要访问的 微服务名称,但是并没有指定端口号到底是 8001, 还是 8002.
|
步骤 8 : 服务类
服务类,数据从 productClientFeign 中获取
|
步骤 9 : 控制器
控制器,把数据取出来放在 product.html 中
|
步骤 10 : products.html
遍历数据
|
步骤 11 : 启动类
启动类, 注解多了个 @EnableFeignClients, 表示用于使用 Feign 方式。
|
步骤 12 : application.yml
配置类,指定了 eureka server 的地址,以及自己的名称。 另外是一些 thymeleaf 的默认配置。
|
步骤 13 : 启动并访问
运行 ProductViewServiceFeignApplication以启动 微服务,然后访问地址:
http://127.0.0.1:8012/products
多刷新几遍,会发现这个端口有时候是 8001,有时候是8002. 从而观察到访问 数据服务集群,客户端负载均衡的效果。
步骤 14 : 调用图
如图所示:
1. 首先数据微服务和视图微服务都被 eureka 管理起来了。
2. 数据服务是由两个实例的集群组成的,端口分别是 8001 , 8002
3. 视图微服务通过 注册中心调用微服务, 然后负载均衡到 8001 或者 8002 端口的应用上。
步骤 15 : ribbon 和 feign
因为 Feign 是对 Ribbon 的封装,而且也是主要方式,所以后续学习我们就会都使用 feign, 而不再使用 Ribbon了。
更多内容,点击了解: http://how2j.cn/k/springcloud/springcloud-feign/2041.html