欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

springcloud-gateway实现

时间:2023-06-08
Spring Cloud Gateway 的三大核心概念

Route (路由): 路由是构建网关的基本模块,它由 ID,目标 URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
Predicate(断言):参考的是 java8 的 java.util.function.Predicate 开发人员可以匹配 HTTP 请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
Filter(过滤):指的是 Spring 框架中 GatewayFilter 的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改

Spring Cloud Gateway具体实现

pom文件

<?xml version="1.0" encoding="UTF-8"?> 4.0.0 spring-cloud-demo com.xx.job 1.0-SNAPSHOT cloud-gateway-gateway9527 1.8 junit junit 4.11 mysql mysql-connector-java com.alibaba druid org.projectlombok lombok org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-openfeign org.springframework.cloud spring-cloud-starter-netflix-hystrix org.springframework.cloud spring-cloud-starter-gateway io.projectreactor.netty reactor-netty 0.9.14.RELEASE

yml文件

server: port: 9527spring: application: name: cloud-gateway-gateway9527 cloud: gateway: routes: - id: payment8001 uri: lb://SPRING-CLOUD-PAYMENT predicates: - Path=/payment/selectById/**eureka: instance: instance-id: cloud-gateway-gateway9527 client: #表示是否将自己注册进EurekaServer,默认为true register-with-eureka: true # 是否从EurekaServer抓取已有的注册信息,默认为毛白前,单节点无所谓,集群必须设置为true,才能配合ribbon使用负载均衡 fetch-registry: true service-url: defaultZone: http://localhost:7001/eureka,http://localhost:7002/eureka

主启动类

package com.xx.job.cloudgatewaygateway9527;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@EnableEurekaClient@SpringBootApplication@EnableDiscoveryClientpublic class CloudGatewayGateway9527Application { public static void main(String[] args) { SpringApplication.run(CloudGatewayGateway9527Application.class, args); }}

 gateway的两种配置方式

方式一:上面的yml配置方式

方式二:java类配置

package com.xx.job.cloudgatewaygateway9527.config;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class GatewayConfig { @Bean public RouteLocator routeLocator(RouteLocatorBuilder routeLocatorBuilder){ RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes(); RouteLocator build = routes.route("payment8001", r -> r.path("/payment/selectById/**").uri("lb://SPRING-CLOUD-PAYMENT")) // .route("payment8002", r -> r.path("/payment/get/**").uri("http://127.0.0.1:8002")) .build(); return build; }}

git:spring-cloud-demo: spring-cloud-demo试例

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。