中国领先的工业平台

返回贤集网 返回微头条
贤集网技术微头条APP获取

详解spring cloud构建微服务架构的网关(API GateWay)

 山东大明消毒科技有限公司

下载贤集网APP入驻自媒体

前言


在我们前面的博客中讲到,当服务A需要调用服务B的时候,只需要从Eureka中获取B服务的注册实例,然后使用Feign来调用B的服务,使用Ribbon来实现负载均衡,但是,当我们同时向客户端暴漏多个服务的时候,客户端怎么调用我们暴漏的服务了,如果我们还想加入安全认证,权限控制,过滤器以及动态路由等特性了,那么就需要使用Zuul来实现API GateWay了,下面,我们先来看下Zuul怎么使用。


一、加入Zuul的依赖

org.springframework.cloudspring-cloud-starter-zuulorg.springframework.cloudspring-cloud-starter-eureka复制代码由于,我们需要将Zuul服务注册到Eureka Server上,同时从Eureka Server上发现注册的服务,所以这里我们加上了Eureka的依赖。


二、在应用Application主类上开启Zuul支持

@SpringBootApplication@EnableZuulProxy // 使用@EnableZuulProxy来开启Zuul的支持,如果你不想使用Zuul提供的Filter和反向代理的功能的话,此处可以使用@EnableZuulServer注解public class ZuulApplication {public static void main(String[] args) {SpringApplication.run(ZuulApplication.class, args);}}复制代码三、在application.yml中增加Zuul的基础配置信息

spring:application:name: gateway-zuul # 应用名server:port: 8768 #Zuul Server的端口号eureka:client:service-url:defaultZone: http://localhost:8761/eurekainstance:prefer-ip-address: true复制代码四、在application.yml中增加服务路由配置


前提:在Eureka Server已经注册了2个服务,分别是:springboot-h2-service和springboot-rest-template-feign,其中springboot-rest-template-feign服务会调用springboot-h2-service服务,springboot-rest-template-feign服务是我们对外提供的服务,也就是说,springboot-rest-template-feign服务是我们暴漏给客户端调用的。

# 路由配置方式一#zuul:# routes:# springboot-rest-template-feign: /templateservice/** #所有请求springboot-rest-template-feign的请求,都会被拦截,并且转发到templateservice上# 路由配置方式二zuul:routes:api-contract: # 其中api-contract是路由名称,可以随便定义,但是path和service-id需要一一对应path: /templateservice/**service-id: springboot-rest-template-feign # springboot-rest-template-feign为注册到Eureka上的服务名ribbon:NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule # 配置服务端负载均衡策略复制代码

最新回复

还没有人回复哦,抢沙发吧~

发布回复

为您推荐

热门交流