欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微服务-服务网关

程序员文章站 2022-06-03 20:23:25
...

服务网关

gateway

  1. pom.xmx
<!-- 注册中心:nacos -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!-- 服务调用:openfeign -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- 网关:gatway -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 启动类标注注解:@EnableDiscoveryClient
  2. 配置文件:application.yml
server:
  port: 10016

spring: 
	application: 
		name: service-gateway
	cloud:
		nacos: 
			discovery: 
				server-addr: 127.0.0.1:50101
		gateway:
			discovery: 
				locator: 
					enable: true  # 开启服务发现路由
			routes: 
				- id: service-a  # 不重复即可
				  name: lb://service-a   # 服务名或(ip+端口:http://localhost:8080)
			      predicates: 
			      	- path=/aaa/**   # 断言:匹配规则
			     
			    - id: service-b  
				  name: lb://service-b 
			      predicates: 
			      	- path=/bbb/**  
			
  1. 自定义全局Filter

    • 实现 GatewayFilterFactory接口,重写 shortcutFieldOrder方法
    • 编写的过滤器类必须要以 GatewayFilterFactory结尾
    • 自定义过滤器的名字为,GatewayFilterFactory前面的字符