SpringCloud 微服务系列——【Gateway、Config组件使用】

奋斗吧
奋斗吧
擅长邻域:未填写

标签: SpringCloud 微服务系列——【Gateway、Config组件使用】

2023-05-27 18:23:27 51浏览

✅作者简介:2022年博客新星。热爱国学的Java后端开发者,修心和技术同步精进。🍊个人信条:不迁怒,不贰过。小知识,大智慧。🥭本文内容:SpringCloud 微服务系列——【Gateway、Config组件使用】

在这里插入图片描述

✅作者简介:2022年博客新星 第八。热爱国学的Java后端开发者,修心和技术同步精进。
🍎个人主页:Java Fans的博客
🍊个人信条:不迁怒,不贰过。小知识,大智慧。
💞当前专栏:SpringCloud 微服务学习专栏
✨特色专栏:国学周更-心性养成之路
🥭本文内容:SpringCloud 微服务系列——【Gateway、Config组件使用】

在这里插入图片描述

Gateway组件使用

什么是服务网关

网关统一服务入口,可方便实现对平台众多服务接口进行管控,对访问服务的身份认证、防报文重放与防数据篡改、功能调用的业务鉴权、响应数据的脱敏、流量与并发控制,甚至基于API调用的计量或者计费等等。

  • 网关 = 路由转发 + 过滤器+负载均衡
    路由转发:接收一切外界请求,转发到后端的微服务上去
  • 网关组件在微服务中架构

在这里插入图片描述

zuul 1.x 2.x(netflix 组件)

Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application. As an edge service application, Zuul is built to enable dynamic routing, monitoring, resiliency and security.

zul是从设备和网站到Netflix流媒体应用程序后端的所有请求的前门。作为一个边缘服务应用程序,zul被构建为支持动态路由、监视、弹性和安全性

zuul版本说明

  • 目前zuul组件已经从1.0更新到2.0,但是作为springcloud官方不再推荐使用zuul2.0,但是依然支持zuul2

gateway (spring)

This project provides a library for building an API Gateway on top of Spring MVC. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.

- 这个项目提供了一个在springmvc之上构建API网关的库。springcloudgateway旨在提
供一种简单而有效的方法来路由到api,并为api提供横切关注点,比如:安全性、监控/度
量和弹性。

# 1.特性
- 基于springboot2.x 和 spring webFlux 和 Reactor 构建 响应式异步非阻塞IO模
型
- 动态路由
- 请求过滤

开发网关动态路由

网关配置有两种方式

  • 一种是快捷方式(Java代码编写网关)
  • 一种是完全展开方式(配置文件方式)[推荐]

1.创建项目引入网关依赖

<!--引入gateway网关依赖-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

快捷方式配置路由

编写网关配置

server:
  port: 9999
spring:
  application:
    name: GATEWAY
  cloud:
    consul:
      host: localhost
      port: 8500
    gateway:
      routes:
        - id: category_router #路由唯一标识
          uri: http://localhost:9090 #路由转发地址
          predicates:
            - Path=/cat1

        - id: priducts_router #路由唯一标识
          uri: http://localhost:8787 #路由转发地址
          predicates:
            - Path=/p1    #/p1 ,/p2 ,/p3 多个路径映射
            
 ---------------------------------------------------------------------------
         - id: priducts_router #路由唯一标识
           uri: http://localhost:8787 #路由转发地址
           predicates:
             - Path=/p/**

启动gateway网关项目

  • 直接启动报错:

在这里插入图片描述

在启动日志中发现,gateway为了效率使用webflux进行异步非阻塞模型的实现,因此和原来的web包冲突,去掉原来的web即可

在这里插入图片描述

再次启动成功启动

在这里插入图片描述

测试网关路由转发

  • 测试通过网关访问目录服务: http://localhost:9999/cat1
  • 测试通过网关访问商品服务: http://localhost:9999/p1

java方式配置路由

官网:https://spring.io/projects/spring-cloud-gateway

在这里插入图片描述

@Configuration
public class GateWayConfig {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return  builder.routes()
                .route("category_router",r->r.path("/cat1")
                        .uri("http://localhost:9090"))
                .route("product_router",r->r.path("/p1")
                        .uri("http://localhost:8787"))
                .build();
    }
}

查看网关路由规则列表

gateway提供路由访问规则列表的web界面,但是默认是关闭的,如果想要查看服务路由规则可以在配置文件中开启

management:
  endpoints:
    web:
      exposure:
        include: "*"   #开启所有web端点暴露
- 访问路由管理列表地址
- http://localhost:8989/actuator/gateway/routes

配置路由服务负载均衡

spring:
  application:
    name: gateway
  cloud:
    consul:
      host: localhost
      port: 8500
    gateway:
      routes:
         - id: priducts_router #路由唯一标识
          uri: lb://PRODUCTS
          predicates:
            - Path=/p/**
            
      discovery:
        locator:
          enabled: true 			#开启根据服务名动态获取路由

常用路由predicate(断言,验证)

Gateway支持多种方式的predicate

在这里插入图片描述

- After=2023-01-06T11:32:53.698+08:00[Asia/Shanghai]`指定日期之后的请求进行路由

- Before=2021-12-25T23:29:38.905+08:00[Asia/Shanghai]指定日期之前的请求进行路由

- Between=2021-12-25T23:29:38.905+08:00[Asia/Shanghai], 2021-12-27T23:29:38.905+08:00[Asia/Shanghai]
- Cookie=username,mosin					    基于指定cookie的请求进行路由
- Cookie=username,[A-Za-z0-9]+				基于指定cookie的请求进行路由	
curl http://localhost:8989/user/findAll --cookie "username=zhangsna"
- Header=X-Request-Id, \d ``基于请求头中的指定属性的正则匹配路由(这里全是整数)
curl http://localhost:8989/user/findAll -H "X-Request-Id:11"
- Method=GET,POST		 		基于指定的请求方式请求进行路由

常用的Filter以及自定义filter

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

官网: https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.3.RELEASE/reference/html/#gatewayfilter-factories

  • 路由过滤器允许以某种方式修改传入的HTTP请求或传出的HTTP响应。路由筛选器的作用域是特定路由。springcloudgateway包括许多内置的GatewayFilter工厂。

  • 作用

    当我们有很多个服务时,比如下图中的user-service、order-service、product-service等服务,客户端请求各个服务的Api时,每个服务都需要做相同的事情,比如鉴权、限流、日志输出等。

在这里插入图片描述

在这里插入图片描述

使用内置过滤器

在这里插入图片描述

 filters:
    - AddRequestHeader=user_name, mosin				增加请求头的filter`
    - AddRequestParameter=color, blue				    增加请求参数的filterr`
    - AddResponseHeader=X-Response-Red, AAA				增加响应头filter`
    - PrefixPath=/emp									增加前缀的filter`
    - StripPrefix=2										去掉前缀的filter`

Config组件使用

什么是Config

config(配置)又称为 统一配置中心顾名思义,就是将配置统一管理,配置统一管理的好处是在日后大规模集群部署服务应用时相同的服务配置一致,日后再修改配置只需要统一修改全部同步,不需要一个一个服务手动维护。

统一配置中心组件流程图

在这里插入图片描述

Config Server 开发

1.引入依赖

<!--引入统一配置中心-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-config-server</artifactId>
</dependency>

2.开启统一配置中心服务

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

3.修改配置文件

server:
  port: 8848
spring:
  application:
    name: CONFIGSERVER
  cloud:
    consul:
      port: 8500
      host: 127.0.0.1

4.直接启动服务报错

在这里插入图片描述

没有指定远程仓库的相关配置

5.创建远程仓库

在这里插入图片描述

6.复制仓库地址

在这里插入图片描述

7.在统一配置中心服务中修改配置文件指向远程仓库地址

spring:
  cloud:
    config:
          server:
            git:
              uri: https://gitee.com/classmeng/config.git # 配置远程仓库的地址
             # username:
             # password:   私有仓库需要设置用户名和密码
            default-label: master  #配置分支

8.再次启动统一配置中心

9.拉取远端配置 [三种方式][]

    1. http://localhost:8848/configclient-xxx.yml
    1. http://localhost:7878/test-xxxx.json
    1. http://localhost:7878/test-xxxx.yml

Config Client 开发

1.引入依赖

<!--引入config client-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

2.修改配置文件

spring:
  cloud:
    config:
      discovery:
        enabled: true   #开启根据服务id 获取configServer ip地址
        service-id: CONFIGSERVER
      label: master   #分支
      name: configclient  #文件的名字
      profile: dev   #配置环境  哪个文件生效
    consul:
      port: 8500
      host: localhost

3.启动报错

在这里插入图片描述

在这里插入图片描述

原因分析

项目中目前使用的是application.yml启动项目,使用这个配置文件在springboot项目启动过程中不会等待远程配置拉取,直接根据配置文件中内容启动,因此当需要注册中心,服务端口等信息时,远程配置还没有拉取到,所以直接报错

在这里插入图片描述

解决方案

应该在项目启动时先等待拉取远程配置,拉取远程配置成功之后再根据远程配置信息启动即可,为了完成上述要求springboot官方提供了一种解决方案,就是在使用统一配置中心时应该将微服务的配置文件名修改为bootstrap.(properties|yml),bootstrap.properties作为配置启动项目时,会优先拉取远程配置,远程配置拉取成功之后根据远程配置启动当前应用

在这里插入图片描述

再次启动服务

在这里插入图片描述

在这里插入图片描述

手动配置刷新

在生产环境中,微服务可能非常多,每次修改完远端配置之后,不可能对所有服务进行重新启动,这个时候需要让修改配置的服务能够刷新远端修改之后的配置,从而不要每次重启服务才能生效,进一步提高微服务系统的维护效率。在springcloud中也为我们提供了手动刷新配置和自动刷新配置两种策略,这里我们先使用手动配置文件刷新。

在config client端加入刷新暴露端点

management.endpoints.web.exposure.include=*          #开启所有web端点暴露
-----------------------------------yml--------------------------------------
management:
  endpoints:
    web:
      exposure:
        include: "*"

在这里插入图片描述

在需要刷新代码的类中加入刷新配置的注解

@RestController
@RefreshScope(proxyMode = ScopedProxyMode.DEFAULT)  //不重启服务实现数据的刷新
public class ConfigController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${name}")
    private  String name;

    @GetMapping("/demo")
    public String demo01(){
        logger.info("name{}",name);
        return "configClient ok:"+name;
    }
}

修改之后在访问

  • 发现并没有自动刷新配置?
  • 必须调用刷新配置接口才能刷新配置

手动调用刷新配置接口

POST http://localhost:8999/actuator/refresh  #向当前微服务发送post请求 刷新数据

curl -X POST http://localhost:8889/actuator/refresh

在这里插入图片描述

在这里插入图片描述


  码文不易,本篇文章就介绍到这里,如果想要学习更多Java系列知识点击关注博主,博主带你零基础学习Java知识。与此同时,对于日常生活有困扰的朋友,欢迎阅读我的第四栏目《国学周更—心性养成之路》,学习技术的同时,我们也注重了心性的养成。

在这里插入图片描述

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

客服QQ 1913284695