注:本教程均是参考"程序猿DD"大佬的SpringCloud教程:http://blog.didispace.com/spring-cloud-learning/实践结合自己的理解和总结编写
服务网关:api网关、路由、负载均衡
不同的微服务一般有不同的服务地址,对外暴露的接口一般需要调用多个服务的接口才能够完成,比如订单服务需要用到库存接口、商品信息接口、用户下单、支付等接口,如果对外暴露的接口直接和每个微服务直接进行通信会存在以下问题:
- 1.客户端会多次请求不同微服务,增加客户端的复杂性
- 2.存在跨域请求,在一定场景下处理相对复杂
- 3.认证复杂,每一个服务都需要独立认证
- 4.难以重构,随着项目的迭代,可能需要重新划分微服务,如果客户端直接和微服务通信,那么重构会难以实施
- 5.某些微服务可能使用了其他协议,直接访问有一定困难
服务网关就是为了解决上述问题诞生,网关是介于客户端和服务器之间的中间层,所有外部请求都如下图所示
这样客户端只需要和网关交互,而无需直接调用特定微服务的接口,而且方便监控,易于认证,减少客户端和各个微服务之间的交互次数
服务网关服务
1.创建项目api-gateway
2.添加pom.xml配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
3.启动类
@EnableZuulProxy
@SpringCloudApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ApiGatewayApplication.class).web(true).run(args);
}
}
4.application.properties配置
spring.application.name=api-gateway
server.port=1101
eureka.client.service-url.defaultZone=http://localhost:1001/eureka/
5.其他说明
###没有服务治理框架的帮助下的路由配置
##/user-service/**规则的请求路由到http://localhost:8080,比如当请求
##http://localhost:1101/user-service/hello被发送到API网关上时,由于
##/user-service/hello能够被上述配置的path规则匹配,请求将会路由到
##http://localhost:8080/hello
#zuul.routes.user-service.path=/user-service/**
#zuul.routes.user-service.url=http://localhost:8080
##该配置实现了对符合/user-service/**规则的请求路径转发到http://localhost:8080/和http://localhost:8081/两个实例地址的路由规则。
##它的配置方式与服务路由的配置方式一样,都采用了zuul.routes.<route>.path与zuul.routes.<route>.serviceId参数对的映射方式,
##只是这里的serviceId是由用户手工命名的服务名称,配合<serviceId>.ribbon.listOfServers参数实现服务与实例的维护。
##由于存在多个实例,API网关在进行路由转发时需要实现负载均衡策略,
##于是这里还需要Spring Cloud Ribbon的配合。
##由于在Spring Cloud Zuul中自带了对Ribbon的依赖,
##所以我们只需要做一些配置即可
#zuul.routes.user-service.path=/user-service/**
#zuul.routes.user-service.service-id=user-service
##默认情况下ribbon会根据服务发现机制来获取配置服务名对应的实例清单,所以如果没有整合服务治理框架
##需要将参数配置为false,不然配置的serviceId无法获取到服务实例清单
#ribbon.eureka.enabled=false
##该参数内容与zuul.routes.<route>.serviceId的配置相对应,开头的user-service对应了serviceId的值,
##这两个参数的配置相当于在该应用内部手工维护了服务与实例的对应关系
#user-service.ribbon.listOfServers=http://localhost:8080/,http://localhost:8081/
###整合了服务治理框架Eureka或者Consul的配置
##对符合/user-service/**规则的请求路径转发到名为user-service的服务实例上去的路由规则
##格式为zuul.routes.<route>.path=<path>;zuul.routes.<route>.serviceId=<serviceId>
#zuul.routes.user-service.path=/user-service/**
#zuul.routes.user-service.service-id=user-service
##更加简单的配置zuul.routes.<serviceId>=<path>,其实等同于上面的两个配置结合
#zuul.routes.user-service=/user-service/**