springCloud微服务组件:Gateway(网关)

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值