八、项目接入网关gateway

本文介绍了如何使用Spring Cloud Gateway构建微服务网关,包括配置POM文件,设置服务发现、断路器和路由规则。通过启用Eureka客户端,配置Hystrix实现服务降级,并提供了默认的降级处理。此外,还讨论了Zuul与Spring Gateway的区别,以及后续可能涉及的自定义过滤器和Swagger文档聚合。
摘要由CSDN通过智能技术生成

新建项目

依赖注入pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.yyzh</groupId>
    <artifactId>hello-gateway</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>hello-gateway</name>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>

        <lombok.version>1.18.6</lombok.version>
    </properties>

    <dependencies>
        <!-- eureka client 端包 -->
        <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-netflix-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <!--监控和管理-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <optional>true</optional>
        </dependency>

    </dependencies>

    <!--管理spring cloud所有组件的版本-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件

server:
  port: 8522

#properties:
#  root-path: /service1

spring:
  application:
    name: hello-gateway
  # 开启 Gateway 服务注册中心服务发现
  cloud:
    gateway:
#      enabled: true # 默认为true启动网关,如果项目中引用的jar包而不想启用网关,可以改为false
      discovery:
        locator:
          enabled: true # 当访问http://网关地址/服务名称(大写)/**地址会自动转发到http://服务名称(大写)/**地址,如果为false就不会自动转发
          lowerCaseServiceId: true  # 为true表示服务名称(小写)
      routes:
        - id: hello-tools
          uri: lb://hello-tools # lb 代表从注册中心获取服务
          predicates: # 断言
            - Path=/hellos/**
          filters:
            - StripPrefix=1 #StripPrefix网关过滤器工厂采用一个参数StripPrefix。 StripPrefix参数表示在将请求发送到下游之前从请求中剥离的路径个数
#      #全局默认filters:default-filters中 下面的先执行 所以 Retry在下面 Hystrix在上面 (即 先重试在断路)
      default-filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/defaultfallback
#        - name: Retry
#          args:
#            retries: 3  # 在Eureka注册列表中有一个节点挂掉了,在短时间内,列表没有更新,还会调用挂掉的节点,可以通过失败重试调用其他节点
#            statuses: BAD_GATEWAY
#
#    loadbalancer:
#      retry:
#        enabled: true
#
hystrix:
  command:
    default:  #  这个地方是上面hystrix的name,timeout默认是1s,   default为全局配置默认
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000

##  actuator配置
management:
  endpoints:
    web:
      exposure:
        # 显式配置不需要权限验证对外开放的端点
        include: "*"

# 更改Eureka更新频率将打破服务器的自我保护功能,生产环境下不建议自定义这些配置。
eureka:
  instance:
    prefer-ip-address: false #使⽤ip注册,否则会使⽤主机名注册了(此处考虑到对⽼版本的兼容,新版本经过实验都是ip)
    lease-expiration-duration-in-seconds: 90  # 续约到期时间(默认90秒)
    lease-renewal-interval-in-seconds: 30 # 续约更新时间间隔(默认30秒)
  client:
    healthcheck:
      enabled:  true    # 开启健康检查(需要spring-boot-starter-actuator依赖)
    register-with-eureka: true
    registry-fetch-interval-seconds: 30
    serviceUrl: #注册中心的注册地址
      defaultZone: http://admin:admin@localhost:8761/eureka/

服务降级可视化返回

package com.yyzh.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class DefaultHystrixController {

    @RequestMapping("/defaultfallback")
    public String defaultfallback(){

        log.info("服务降级中");
        return "服务异常";
    }
}

启动类

package com.yyzh;

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);
        System.out.println("gateway 服务启动...");
    }
}

验证

启动

  1. register注册中心
  2. hello-tools客户端
  3. gateway网关

验证网关正常转发

在这里插入图片描述

验证端口挂掉服务降级

关掉hello-tools,再调用接口

在这里插入图片描述

拓展

以上为项目接入gateway基本方式,拓展见如下:

  • zuul和spring gateway区别
  • gateway自定义过滤器(权限验证)、swagger文档聚合,这两个后续会另开专栏,该专栏旨在了解并应用spring cloud全家桶搭建微服务,较初级
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值