Gateway网关

1. 网关介绍

注意:spring cloud gateway 依赖,需要在spring boot和spring webflux提供的netty下运行,不能在Servlet容器中运行,也就是不能同时依赖spring-boot-starter-web

2. 使用

2.1 依赖

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

项目添加依赖后,直接启动主类GatewayApplication测试项目依赖包是否有冲突,正常启动如下图所示:
在这里插入图片描述
项目内没有任何方法,直接访问http://localhost:8080/xxx,出现白页,说明正常启动。
在这里插入图片描述

2.2 添加过滤规则和过滤器

在配置中配置要拦截的请求路径Path,然后编写过滤器进行拦截过滤。

2.3.3.1 yml配置
server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
        - id: provider
          uri: http://localhost:8081/
          ## 意思是对http://localhost:8080/provider/**的请求进行拦截,转发至http://localhost:8081/**
          predicates:
            - Path=/provider/**
          ## 表示在将请求发送到下游之前从请求中剥离的路径个数,剥离1个,即http://localhost:8081/**
          filters:
            - StripPrefix=1

        - id: consumer
          uri: http://localhost:8083/
          ## 意思是对http://localhost:8080/consumer/**的请求进行拦截,转发至http://localhost:8083/consumer/**
          predicates:
            - Path=/consumer/** 

2.3.3.2 过滤器

自定义基于url的过滤器,实现GlobalFilter接口,重写filter方法。

package com.gs.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class UrlFilter implements GlobalFilter {

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String url = request.getURI().getPath();
		//TODO 拦截特定URL地址
		System.out.println("url: " + url);
		return chain.filter(exchange);
	}
}

2.3 测试

2.3.1 服务1provider

启动端口8081,内部有/index方法,输出一句话。
直接访问http://localhost:8081/index
在这里插入图片描述

2.3.2 服务2consumer

启动端口8083,内部有/consumer方法,实现对服务1provider的远程调用,并输出。
直接访问http://localhost:8083/consumer
在这里插入图片描述

2.3.3 网关

网关内部只实现了对url的拦截和转发,启动端口8080

  • 访问http://localhost:8080/provider/index,成功拦截并转发到了服务1provider上。
    在这里插入图片描述

  • 访问http://localhost:8080/consumer,成功拦截并转发到了服务2consumer上。
    如果provider是个集群,再有一个8082端口的服务
    在这里插入图片描述
    在这里插入图片描述

  • 访问http://localhost:8080/index,不满足配置的拦截规则,无法转发,而此时网关项目也没有/index的方法,故出现404,依旧证明网关拦截配置成功!
    在这里插入图片描述

遇到的问题

集成spring-cloud-gateway 启动报以下错误:

**********************************************************

Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

**********************************************************


2020-03-21 11:14:33.917  WARN 14524 --- [  restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
2020-03-21 11:14:33.920  INFO 14524 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-03-21 11:14:33.931  INFO 14524 --- [  restartedMain] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-21 11:14:34.089 ERROR 14524 --- [  restartedMain] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gatewayConfigurationService' defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]: Unsatisfied dependency expressed through method 'gatewayConfigurationService' parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:787) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:528) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at com.dolphin.GateWayApplication.main(GateWayApplication.java:21) [classes/:na]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]
	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.0.RELEASE.jar:2.2.0.RELEASE]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.core.convert.ConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value=webFluxConversionService)}
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:874) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:778) ~[spring-beans-5.2.0.RELEASE.jar:5.2.0.RELEASE]
	... 24 common frames omitted

Disconnected from the target VM, address: '127.0.0.1:50299', transport: 'socket'

Process finished with exit code 0

因为spring cloud gateway 依赖,需要在spring boot和spring webflux提供的netty下运行,不能在Servlet容器中运行,也就是不能同时依赖spring-boot-starter-web。检查项目是否依赖web模块,如果有,移除再试一次。

### Spring Cloud Gateway 网关配置与使用教程 #### 1. 添加依赖 为了在项目中集成 Spring Cloud Gateway,需要在项目的 `pom.xml` 文件中添加以下 Maven 依赖项[^1]: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> ``` 此依赖会自动引入必要的组件来支持网关功能。 --- #### 2. 配置文件设置 在 `application.yml` 或 `application.properties` 中定义网关的路由规则和其他相关参数。以下是基于 YAML 的示例配置[^1]: ```yaml spring: cloud: gateway: routes: - id: service_a_route # 路由 ID (唯一标识符) uri: http://localhost:8081 # 后端服务地址 predicates: - Path=/service-a/** # 请求路径匹配条件 filters: - StripPrefix=1 # 去除前缀 /service-a/ ``` 在此配置中: - **id**: 定义唯一的路由名称。 - **uri**: 指定目标微服务的实际 URL 地址。 - **predicates**: 设置用于匹配 HTTP 请求的条件(例如路径、方法、查询参数等)。 - **filters**: 对请求或响应应用过滤器操作(如修改头信息、重写路径等)。 --- #### 3. 自定义过滤器 可以通过编写自定义全局过滤器扩展 Gateway 功能。下面展示了一个简单的日志记录过滤器实现[^1]: ```java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; @Component public class LoggingFilter implements GlobalFilter, Ordered { private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String path = exchange.getRequest().getPath().value(); logger.info("Request received for path: {}", path); return chain.filter(exchange).then(Mono.fromRunnable(() -> { int status = exchange.getResponse().getStatusCode().value(); logger.info("Response sent with status code: {}", status); })); } @Override public int getOrder() { return HIGHEST_PRECEDENCE; // 控制执行顺序 } } ``` 该类实现了 `GlobalFilter` 接口,并覆盖了其核心逻辑以打印请求和响应的日志信息。 --- #### 4. 测试网关功能 启动应用程序后,可通过浏览器或其他工具发送测试请求验证网关行为。假设已配置 `/service-a/endpoint` 映射至本地运行的服务,则访问如下 URL 即可触发相应处理流程: ``` http://localhost:<gateway-port>/service-a/endpoint ``` 如果一切正常工作,应看到来自指定后台服务的数据返回。 --- #### 5. 进阶特性 除了基本的功能外,Spring Cloud Gateway 支持更多高级选项,比如限流保护、身份验证以及动态路由更新等。这些都可以通过额外插件或者调整现有框架结构达成目的。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值