springCloud微服务组件:Gateway(网关)
基本配置
1.导包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
2.编写启动类
@SpringBootApplication
public class GateWayApp {
public static void main(String[] args) {
SpringApplication.run(GateWayApp.class,args);
}
}
3.编写配置文件
# 配置网关的端口
server:
port: 80
# 配置网关的名称
spring:
application:
name: GATEWAY=SERVER
#配置网关的相关属性
cloud:
gateway:
#路由配置,转发规则
routes:
# 唯一标识,一般写网关对应的微服务名字
- id: NACOS-CONSUMER
# 网关对应微服务的路径
uri: http://localhost:8000
# 用户请求网关的地址http://localhost:80后面的地址如果与这个规则一样,网关则会找到相对应的服务地址:
# 比如http://localhost:8000,然后再用这个地址与用户请求的地址http://localhost:80后面的地址作拼接
# 1.用户请求网关的地址http://localhost:80/hello/find
# 2.跟这个规则相同,找到相对应的服务地址http://localhost:8000
# 3.用服务地址与用户输入的地址/hello/find作拼接
# 4.得到最终服务的地址,http://localhost:8000/hello/find
predicates:
- Path=/hello/**
静态路由
刚刚写的配置文件中的服务地址是写死的,如果服务端口这些发生改变,配置文件也要跟着改变。
增加一个静态配置
- id: NACOS-PROVIDER
uri: http://localhost:9000
predicates:
- Path=/hello/**
动态路由
将网关这个模块改变成注册中心的客户端,网关就可以动态的从注册中心获取到各个服务的动态地址
- 在yaml配置文件中增加对应的注册中心地址
nacos:
discovery:
server-addr: 127.0.0.1:8848
- 将静态地址改成动态,将uri属性改为lb://服务实例名称
- id: NACOS-CONSUMER
# 网关对应微服务的路径
uri: lb://NACOS-CONSUMER
# 用户请求网关的地址http://localhost:80后面的地址如果与这个规则一样,网关则会找到相对应的服务地址:
# 比如http://localhost:8000,然后再用这个地址与用户请求的地址http://localhost:80后面的地址作拼接
# 1.用户请求网关的地址http://localhost:80/hello/find
# 2.跟这个规则相同,找到相对应的服务地址http://localhost:8000
# 3.用服务地址与用户输入的地址/hello/find作拼接
# 4.得到最终服务的地址,http://localhost:8000/hello/find
predicates:
- Path=/hello/**
- id: NACOS-PROVIDER
uri: lb://NACOS-PROVIDER
predicates:
- Path=/hello/**
添加微服务名称
在用户请求地址前添加微服务的名称指定访问哪个微服务
# 用户请求地址前添加微服务名称,默认为false,true表示开启
discovery:
locator:
enabled: true