1 搭建注册中心eureka
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
配置 yml文件
server:
port: 7001
eureka:
instance:
hostname: localhost
client:
#声明自己是个服务端
registerWithEureka: false #false表示不向注册中心注册自己
fetchRegistry: false #false表示自己就是注册中心,职责是维护实例,不参加检索
serviceUrl: #设置eureka server的交互地址,即对外暴露的地址
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
2 注册服务到服务中心
server: port: 8001 #指定注册中心地址 eureka: client: serviceUrl: defaultZone: http://localhost:7001/eureka/ #服务的名称 spring: application: name: product-service
3 微服务要引入接口调用jar 实现注解式编程
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在使用Feign的时候,要注意使用requestBody,应该使用@PostMapping
1、执行流程
总到来说,Feign的源码实现的过程如下:
(1)首先通过@EnableFeignCleints注解开启FeignCleint
(2)根据Feign的规则实现接口,并加@FeignCleint注解
(3)程序启动后,会进行包扫描,扫描所有的@ FeignCleint的注解的类,并将这些信息注入到ioc容器中。
(4)当接口的方法被调用,通过jdk的代理,来生成具体的RequesTemplate
(5)RequesTemplate在生成Request
(6)Request交给Client去处理,其中Client可以是HttpUrlConnection、HttpClient也可以是Okhttp
(7)最后Client被封装到LoadBalanceClient类,这个类结合类Ribbon做到了负载均衡。
2、Feign和Ribbon比较优点
(1) feign本身里面就包含有了ribbon,只是对于ribbon进行进一步封装
(2) feign自身是一个声明式的伪http客户端,写起来更加思路清晰和方便
(3) fegin是一个采用基于接口的注解的编程方式,更加简便
4、网关搭建
导入网关jar
<!--客户端jar包,这个在订单微服务,商品微服务都要添加-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- zuuljar包 网关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
server:
port: 6001
#服务的名称
spring:
application:
name: zuul-gateway
#指定注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7001/eureka/
#/order-service/api/v1/order/save?user_id=2&product_id=1
#自定义路由映射
zuul:
routes:
order-service: /apigateway/order/**
product-service: /apigateway/product/**
#统一入口为上面的配置,其他入口忽略
ignored-patterns: /*-service/**
#忽略整个服务,对外提供接口
ignored-services: order-service