Spring Cloud Gateway 入门案例

博主SpringCloudDemo案例:https://github.com/zhangbin1995/SpringCloudDemo
如果对您有帮助,欢迎star~

作为网关来说,网关最重要的功能就是协议适配和协议转发,协议转发也就是基本的路由信息转发,本入门案例将演示一个 Spring Cloud Gateway 的基本路由转发功能。

创建Maven工程

新建Maven工程 Spring-Cloud-api,项目结构如图:
在这里插入图片描述

pom依赖

这里我们引入zuul和注册中心consul的依赖即可

<!--zuul-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
<!--consul-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-all</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>

启动类

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

application.yml

主要配置网关信息

server:
  port: 8001

spring:
  application:
    name: spring-cloud-api

zuul:
  routes:
    user:
      path: /enterprise/**
      serviceId: enterprise

bootstrap.yml

主要配置注册中心信息

spring:
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      discovery:
        healthCheckPath: /application/health
        healthCheckInterval: 5s
        health-check-critical-timeout: 5m
        prefer-ip-address: true
        ip-address: 127.0.0.1

management:
  endpoints:
    web:
      exposure:
        include: '*'
      base-path: /application

这样我们通过zuul实现了一个网关的跳转,启动enterprise服务和spring-cloud-api服务。在未做网关映射的时候,我们要访问enterprise的接口只能直接访问它的接口地址如:http://127.0.0.1:8003/user/queryAll在这里插入图片描述

而进行跳转之后就可以通过网关这边进行访问:http://127.0.0.1:8001/enterprise/user/queryAll
在这里插入图片描述
如上,效果是一样的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值