Spring Cloud 微服务调用链示例
目标
构建完整微服务调用链:Gateway 路由 → 服务发现 → Feign 调用 → Resilience4j 熔断。
架构
Client → Gateway (8080) → User Service (8081)
→ Order Service (8082)
└── Feign → User Service
完整代码
1. Eureka Server(注册中心)
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
# application.properties
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
2. User Service(服务提供者 8081)
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication { ... }
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
public Map<String, Object> getUser(@PathVariable Long id) {
return Map.of("id", id, "name", "Alice", "email", "alice@example.com");
}
}
spring.application.name=user-service
server.port=8081
eureka.client.service-url.defaultZone=http:
3. Order Service(服务消费者 8082)
@FeignClient(name = "user-service", fallbackFactory = UserClientFallback.class)
public interface UserClient {
@GetMapping("/users/{id}")
Map<String, Object> getUser(@PathVariable Long id);
}
@Component
public class UserClientFallback implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
return id -> Map.of("id", id, "error", "User service unavailable");
}
}
@RestController
@RequestMapping("/orders")
public class OrderController {
@Autowired
private UserClient userClient;
@GetMapping("/{id}")
public Map<String, Object> getOrder(@PathVariable Long id) {
Map<String, Object> user = userClient.getUser(1L);
return Map.of(
"orderId", id,
"product", "MacBook Pro",
"user", user
);
}
}
spring.application.name=order-service
server.port=8082
eureka.client.service-url.defaultZone=http:
# Resilience4j 熔断配置
resilience4j.circuitbreaker.instances.user-service.sliding-window-size=10
resilience4j.circuitbreaker.instances.user-service.failure-rate-threshold=50
resilience4j.circuitbreaker.instances.user-service.wait-duration-in-open-state=30s
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderServiceApplication { ... }
4. API Gateway(网关 8080)
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication { ... }
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: user-service
uri: lb:
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- id: order-service
uri: lb:
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1
default-filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
server:
port: 8080
运行步骤
./mvnw spring-boot:run -pl eureka-server
./mvnw spring-boot:run -pl user-service
./mvnw spring-boot:run -pl order-service
./mvnw spring-boot:run -pl gateway
测试
curl http:
预期输出
{
"orderId": 1001,
"product": "MacBook Pro",
"user": {
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
}