网关服务——SpringCloud Gateway

一、使用

1.准备Eureka注册中心

2.准备一个微服务工程

3.搭建Gateway网关微服务

①在maven中添加如下依赖:

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>3.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

②编写配置文件application.yaml

server:
  port: 8472
spring:
  application:
    name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          #开启从注册中心动态创建路由功能,利用微服务名进行路由
          enabled: true
          lower-case-service-id: true
      routes:
        - id: customer  #路由的ID,没有固定规则但要求唯一,建议配合服务名
          # lb:// + ${目标服务的spring.application.name的值}
          uri: http://127.0.0.1:10001  #匹配后提供服务的路由地址
          # 映射的路径 访问符合Path值的路径,转发到响应的uri对应服务下Path
          predicates:
            - Path=/zhang/**  # 断言,路径相匹配的进行路由

        - id: provider
            # lb:// + ${目标服务的spring.application.name的值}
#          uri: http://127.0.0.1:10002
          uri: lb://PROVIDER
            # 映射的路径 访问符合Path值的路径,转发到响应的uri对应服务下Path
          predicates:
              - Path=/zhang/**

#eureka相关配置
eureka:
  instance:
    lease-renewal-interval-in-seconds: 2
    lease-expiration-duration-in-seconds: 10
#    instance-id: cloud-gateway
  client:
    service-url:
      defaultZone: http://127.0.0.1:10000/eureka
    register-with-eureka: true
    fetch-registry: true

# 自动发现工具的本地路由规则是:
# 请求路径 - http://网关IP:网关端口/微服务的服务名/要访问的具体地址
# gateway自动解析,把请求地址中的'微服务的服务名'截取,从Eureka Client发现的服务列表中查看,如果有同名服务,则开始转发。

③主启动类:

package com.example.gateWay;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class GateWayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GateWayApplication.class, args);
    }
}

④测试

http://ip:端口/服务名/接口名

http://localhost:8472/customer/zhang/getSuccessWithHeader

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值