这篇文章主要为大家展示了“spring cloud如何构建微服务架构的网关”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“spring cloud如何构建微服务架构的网关”这篇文章吧。
一、加入Zuul的依赖
<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>
由于,我们需要将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/eureka
instance:
prefer-ip-address: true
四、在application.yml中增加服务路由配置
前提:在Eureka Server已经注册了2个服务,分别是:springboot-h3-service和springboot-rest-template-feign,其中springboot-rest-template-feign服务会调用springboot-h3-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 # 配置服务端负载均衡策略
五、验证
下面我们就可以来进行验证了,在浏览器中输入:http://localhost:8768/templateservice/template/1就可以看到测试结果了。
以上是“spring cloud如何构建微服务架构的网关”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。