Spring Cloud GetWay demo

107 阅读1分钟

以下是一个简单的 Spring Cloud Gateway 的示例代码:

首先,你需要在你的 pom.xml 文件中添加以下依赖:

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

然后,你可以创建一个简单的路由配置类,例如

在这个配置类中,我们使用了 RouteLocatorBuilder 来创建一个路由定位器,然后定义了一个简单的路由规则,

@Configuration
public class GatewayConfig {

      // 断路器回退方法,返回一个字符串
    String circuitbreakerfallback() {
        return "This is a fallback";
    }

    // 自定义路由定位器方法,传入参数为 RouteLocatorBuilder 对象,返回一个 RouteLocator 对象
  @Bean
  public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        // 使用 builder 对象创建路由规则
        return builder.routes()
            // path_route:根据路径定位路由,将 /get 路径定位到 http://httpbin.org

            .route("path_route", r  -> r.path("/get").uri("http://httpbin.org"))

            // host_route:根据主机名定位路由,将 *.myhost.org 主机名定位到 http://httpbin.org

            .route("host_route", r  -> r.host("*.myhost.org").uri("http://httpbin.org"))

            // rewrite_route:重写路径定位路由,将 *.rewrite.org 主机名下的 /foo/xxx 路径重写为 /xxx 并定位到 http://httpbin.org

            .route("rewrite_route", r  -> r.host("*.rewrite.org").filters(f  -> f.rewritePath("/foo/(?60segment62.*)", "/${segment}")).uri("http://httpbin.org"))

            // circuitbreaker_route:断路器定位路由,将 *.circuitbreaker.org 主机名下的慢速命令使用断路器定位到 http://httpbin.org

            .route("circuitbreaker_route", r  -> r.host("*.circuitbreaker.org").filters(f  -> f.circuitBreaker(c  -> c.setName("slowcmd"))).uri("http://httpbin.org"))

            // circuitbreaker_fallback_route:断路器回退定位路由,将 *.circuitbreakerfallback.org 主机名下的慢速命令使用断路器定位到 http://httpbin.org,并设置回退路径为 /circuitbreakerfallback

            .route("circuitbreaker_fallback_route", r  -> r.host("*.circuitbreakerfallback.org").filters(f  -> f.circuitBreaker(c  -> c.setName("slowcmd").setFallbackUri("forward:/circuitbreakerfallback"))).uri("http://httpbin.org"))

            // limit_route:请求速率限制定位路由,将 *.limited.org 主机名下的 /anything/** 路径限制请求速率并定位到 http://httpbin.org

            .route("limit_route", r  -> r.host("*.limited.org").and().path("/anything/**").filters(f  -> f.requestRateLimiter(c  -> c.setRateLimiter(redisRateLimiter()))).uri("http://httpbin.org"))

            // websocket_route:WebSocket 定位路由,将 /echo 路径定位到 ws://localhost:9000

            .route("websocket_route", r  -> r.path("/echo").uri("ws://localhost:9000"))
            // 构建路由规则并返回
            .build();
    }

    // Spring Web 过滤器链方法,传入参数为 ServerHttpSecurity 对象,抛出异常 Exception,返回一个 SpringWebFilterChain 对象

    SpringWebFilterChain springWebFilterChain(ServerHttpSecurity http) throws Exception {
        // 配置 httpBasic 认证、禁用 CSRF、配置路径权限和其他权限,最后构建并返回
        return http.httpBasic().and().csrf().disable().authorizeExchange().pathMatchers("/anything/**").authenticated().anyExchange().permitAll().and().build();
    }

    // 反应式用户详细信息服务方法,返回一个 MapReactiveUserDetailsService 对象

    MapReactiveUserDetailsService reactiveUserDetailsService() {
        // 创建用户信息
        UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
        // 返回用户信息服务
        return new MapReactiveUserDetailsService(user);
    }
    
    
}

最后,你需要在你的应用程序主类上添加 @EnableDiscoveryClient@SpringBootApplication 注解,例如:

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

这样,你的 Spring Cloud Gateway 应用程序就准备好了。你可以使用以下命令运行该应用程序:

$ mvn spring-boot:run

现在,当你发送到 http://localhost:8080/get 的请求时,它将会被转发到 http://httpbin.org/get。 你可以通过访问 http://localhost:8080/actuator/gateway/routes 来查看路由配置的详情。