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.
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
ServerCodecConfigurerbean 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.propertiesorapplication.ymlsetsserver.port=9000(since you're curlinglocalhost:9000/get). - Remove the custom
ServerCodecConfigurerbean: 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:
Now you can visitmanagement.endpoints.web.exposure.include=gateway,routes,hystrix.stream management.endpoint.gateway.enabled=truehttp://localhost:9000/actuator/gateway/routesto confirm your/getroute 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.
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.
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.
- Make sure your Eureka server is running at
http://localhost:8761before 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

