You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Cloud Gateway:简单路由或降级功能无法正常工作

Hey there, let's work through your Spring Cloud Gateway issues one by one — we'll fix the 404 routing problem in Hoxton.SR7, get Hystrix working properly, and integrate Eureka for service discovery.

1. Fixing the 404 Routing Issue in Hoxton.SR7

First, let's figure out why your route isn't matching in the Hoxton version. The most likely culprits here are:

  • A misconfigured server port
  • Your manually defined ServerCodecConfigurer bean interfering with Gateway's default auto-configuration
  • Missing actuator endpoints to verify route loading

Step-by-Step Fix:

  • Confirm your server port: Make sure your application.properties or application.yml sets server.port=9000 (since you're curling localhost:9000/get).
  • Remove the custom ServerCodecConfigurer bean: Hoxton.SR7 (paired with Spring Boot 2.3.3) automatically configures this bean for Gateway. Defining your own can break the default codec setup needed for route forwarding.
  • Enable Actuator Gateway Endpoints: Add these lines to your config to check if routes are loaded correctly:
    management.endpoints.web.exposure.include=gateway,routes,hystrix.stream
    management.endpoint.gateway.enabled=true
    
    Now you can visit http://localhost:9000/actuator/gateway/routes to confirm your /get route exists in the list.

Corrected DemoApplication Code:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;

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

    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p
                        .path("/get")
                        .filters(f -> f.addRequestHeader("Hello", "Value"))
                        .uri("http://httpbin.org:80"))
                .build();
    }
}

Now re-run your app and test with curl --dump-header - http://localhost:9000/get — you should get the expected 200 response from httpbin.

2. Getting Hystrix Working with Gateway

Hystrix integration in Gateway requires configuring the Hystrix filter in your routes and setting up a fallback endpoint. Here's how to do it properly:

Step 1: Add Hystrix Filter to Your Route

Update your RouteLocator bean to include the Hystrix filter with a fallback URI:

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(p -> p
                    .path("/get")
                    .filters(f -> f
                            .addRequestHeader("Hello", "Value")
                            .hystrix(config -> config
                                    .setName("HttpbinGetCommand")
                                    .setFallbackUri("forward:/fallback")))
                    .uri("http://httpbin.org:80"))
            .build();
}

Step 2: Create a Fallback Controller

Add a simple controller to handle the fallback request when Hystrix triggers:

package com.example.demo;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FallbackController {
    @GetMapping("/fallback")
    public Map<String, String> handleFallback() {
        Map<String, String> fallbackResponse = new HashMap<>();
        fallbackResponse.put("status", "503");
        fallbackResponse.put("message", "Service temporarily unavailable - Hystrix fallback triggered");
        return fallbackResponse;
    }
}

Step 3: Enable Hystrix Dashboard

Add @EnableHystrixDashboard to your DemoApplication class to enable the dashboard:

@SpringBootApplication
@EnableHystrixDashboard
public class DemoApplication {
    // ... existing code ...
}

Now you can access the dashboard at http://localhost:9000/hystrix and enter http://localhost:9000/actuator/hystrix.stream to monitor Hystrix commands.

3. Integrating Eureka Service Discovery

To connect Gateway to Eureka, you just need to add a few configuration properties and update your routes to use service names instead of hardcoded URIs:

Step 1: Configure Eureka Client

Add these lines to your application.properties:

spring.application.name=gateway-service
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
eureka.instance.prefer-ip-address=true

Step 2: Update Route to Use Eureka Service Name

Instead of using a hardcoded URI like http://httpbin.org:80, use lb://{service-name} where {service-name} is the name of your service registered in Eureka. For example:

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
    return builder.routes()
            // Route to a service registered in Eureka
            .route(p -> p
                    .path("/my-service/**")
                    .filters(f -> f.stripPrefix(1)) // Remove the "/my-service" prefix before forwarding
                    .hystrix(config -> config
                            .setName("MyServiceCommand")
                            .setFallbackUri("forward:/service-fallback"))
                    .uri("lb://my-service"))
            // Keep your existing httpbin route for testing
            .route(p -> p
                    .path("/get")
                    .filters(f -> f.addRequestHeader("Hello", "Value"))
                    .hystrix(config -> config
                            .setName("HttpbinGetCommand")
                            .setFallbackUri("forward:/fallback"))
                    .uri("http://httpbin.org:80"))
            .build();
}

The lb:// prefix tells Gateway to use Spring Cloud LoadBalancer to resolve the service from Eureka and distribute requests across instances.

Final Notes
  • Make sure your Eureka server is running at http://localhost:8761 before starting the Gateway.
  • Test the Hystrix fallback by stopping the target service or simulating a timeout — you should see the fallback response instead of an error.
  • If you still run into issues, check the application logs for errors related to route loading, Eureka registration, or Hystrix configuration.

内容的提问来源于stack exchange,提问作者Grim42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 22:12:50