springcloud gateway路由配置
简单介绍
gateway是spring could推出,基于spring5、springboot2.0、Project React,底层使用netty通讯,性能比较高的网关组件 为什么需要网关呢? 如果没有网关的话,调用方需要配置各种的服务,配置了网关之后,只需要统一访问网关,然后由网关请求具体的服务,调用方提供服务的实例是无感知的,而且网关还可以处理路由、安全、日志、监控等与业务无关的功能,使得业务开发更加纯净。 比较重要的概念: 1、路由:由id,目标uri,一系列断言(predicate),过滤器组成,如果断言为true(即匹配),则讲请求发送到真实服务上去。 2、断言(predicate):即匹配规则,可以匹配所http请求的所有内容,匹配成功,就发送请求到真实服务 3、过滤器:在请求被请求前(pre)修改请求头或请求后修改响应体。
配置路由
配置路由有两种方式:1、使用配置文件 2、使用配置类
步骤
导入pom依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> </dependency> <!-- gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- 注册中心eureka --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
主启动类:
@SpringBootApplication @EnableEurekaClient //开启eureka客服端 public class GetawayMain9527 { public static void main(String[] args) { SpringApplication.run(GetawayMain9527.class,args) ; } }
使用配置文件的方式:
server: port: 9527 //eureka注册中心配置 eureka: client: fetch-registry: true register-with-eureka: true service-url: defaultZone: http://localhost:7001/eureka/ spring: application: name: getaway cloud: discovery: enabled: true //开启动态路由配置,根据服务名称负载均衡 gateway: routes: - id: payment //uri: http://localhost:8001 uri: lb://pay //负载均衡的服务名称 predicates: - Path=/payment/**
使用配置类的方式:
@Configuration public class GatewayConfig { @Bean public RouteLocator customrouteLocator(RouteLocatorBuilder builder){ RouteLocatorBuilder.Builder routes = builder.routes(); routes.route("baidu", r -> r.path("/guonei").uri("http://news.baidu.com")).build(); return routes.build() ; } }
通过上面的配置,访问http://localhost:9527就会路由到http://new.baidu.com/guonei