spring-cloud-basics by claude-dev-suite/claude-dev-suite
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-cloud-basics┌─────────────────────────────────────────────────────────────────┐
│ API Gateway │
│ (Spring Cloud Gateway) │
└───────────────────────────┬─────────────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────────────┐
│ Service Discovery │
│ (Eureka / Consul) │
└──────────┬─────────────────┬─────────────────┬──────────────────┘
│ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ Service A │ │ Service B │ │ Service C │
│ (3 inst.) │ │ (2 inst.) │ │ (1 inst.) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└─────────────────┼─────────────────┘
▼
┌────────────────┐
│ Config Server │
└────────────────┘
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
spring:
application:
name: product-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
完整参考:关于 Eureka 高可用和配置服务器的详细信息,请参阅 service-discovery.md。
spring:
cloud:
gateway:
routes:
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**
filters:
- StripPrefix=0
完整参考:关于自定义过滤器和编程式路由的详细信息,请参阅 gateway.md。
@Service
public class ProductClient {
@CircuitBreaker(name = "productService", fallbackMethod = "fallback")
@Retry(name = "productService")
public List<Product> getProducts() {
return restClient.get()
.uri("http://product-service/api/products")
.retrieve()
.body(new ParameterizedTypeReference<>() {});
}
private List<Product> fallback(Exception e) {
return List.of();
}
}
resilience4j:
circuitbreaker:
instances:
productService:
sliding-window-size: 10
failure-rate-threshold: 50
wait-duration-in-open-state: 10s
完整参考:关于重试、舱壁隔离、速率限制器和 Feign 的详细信息,请参阅 resilience.md。
@Service
@RequiredArgsConstructor
public class OrderService {
private final ProductClient productClient;
private final InventoryClient inventoryClient;
private final PaymentClient paymentClient;
@Transactional
public Order createOrder(CreateOrderRequest request) {
// 1. 验证产品
List<Product> products = request.items().stream()
.map(item -> productClient.getProductById(item.productId()))
.toList();
// 2. 验证库存
boolean available = inventoryClient.checkAvailability(request.items());
if (!available) {
throw new InsufficientInventoryException("Items not available");
}
// 3. 创建订单
Order order = Order.create(request.customerId(), products, request.items());
order = orderRepository.save(order);
// 4. 预留库存
inventoryClient.reserveItems(order.getId(), request.items());
// 5. 处理支付(带回滚)
try {
PaymentResult payment = paymentClient.processPayment(
new PaymentRequest(order.getId(), order.getTotal())
);
order.setPaymentId(payment.paymentId());
order.setStatus(OrderStatus.PAID);
} catch (PaymentFailedException e) {
inventoryClient.releaseReservation(order.getId());
order.setStatus(OrderStatus.PAYMENT_FAILED);
throw e;
}
return orderRepository.save(order);
}
}
@Configuration
public class LoadBalancerConfig {
@Bean
@LoadBalanced
public RestClient.Builder loadBalancedRestClientBuilder() {
return RestClient.builder();
}
}
// 用法:使用服务名代替主机地址
restClient.get()
.uri("http://product-service/api/products")
.retrieve()
.body(new ParameterizedTypeReference<>() {});
management:
tracing:
sampling:
probability: 1.0
zipkin:
tracing:
endpoint: http://localhost:9411/api/v2/spans
logging:
pattern:
level: "%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]"
| 应该做 | 不应该做 |
|---|---|
| 对所有服务使用服务发现 | 硬编码服务 URL |
| 实现带降级处理的熔断器 | 忽略故障 |
| 使用配置服务器集中管理配置 | 重复配置 |
| 添加分布式追踪 | 忽视可观测性 |
| 使用 API 网关作为单一入口点 | 直接暴露服务 |
| 错误 | 原因 | 解决方案 |
|---|---|---|
No instances available | 服务未注册 | 验证 Eureka 注册 |
Connection refused | 服务宕机 | 实现熔断器 |
Timeout | 服务响应慢 | 配置适当的超时时间 |
Config not loading | 配置服务器不可达 | 使用 fail-fast: false 或降级处理 |
| 负载均衡不工作 | 缺少 @LoadBalanced | 为 RestClient builder 添加注解 |
| 反模式 | 问题 | 解决方案 |
|---|---|---|
| 硬编码服务 URL | 无法享受服务发现的好处 | 使用服务名称 |
| 没有熔断器 | 级联故障 | 添加 Resilience4j |
| 缺少重试机制 | 瞬时故障 | 配置带退避的重试 |
| 没有配置刷新 | 变更需要重新部署 | 使用 @RefreshScope |
| 处处同步 | 紧耦合 | 在适当的地方使用异步 |
| 问题 | 诊断 | 修复 |
|---|---|---|
| 服务未找到 | 检查 Eureka 仪表盘 | 验证注册 |
| 配置未加载 | 检查配置服务器日志 | 验证路径、配置文件 |
| 熔断器始终打开 | 检查故障率阈值 | 调整阈值 |
| 网关路由失败 | 检查断言 | 验证路由配置 |
| 负载均衡不工作 | 检查 @LoadBalanced | 添加注解 |
| 文件 | 内容 |
|---|---|
| service-discovery.md | Eureka 服务器/客户端,配置服务器 |
| gateway.md | API 网关,过滤器,路由 |
| resilience.md | 熔断器,重试,Feign,测试 |
每周安装次数
1
代码仓库
首次出现
3 天前
安全审计
安装于
amp1
cline1
openclaw1
opencode1
cursor1
kimi-cli1
┌─────────────────────────────────────────────────────────────────┐
│ API Gateway │
│ (Spring Cloud Gateway) │
└───────────────────────────┬─────────────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────────────┐
│ Service Discovery │
│ (Eureka / Consul) │
└──────────┬─────────────────┬─────────────────┬──────────────────┘
│ │ │
┌──────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐
│ Service A │ │ Service B │ │ Service C │
│ (3 inst.) │ │ (2 inst.) │ │ (1 inst.) │
└─────────────┘ └─────────────┘ └─────────────┘
│ │ │
└─────────────────┼─────────────────┘
▼
┌────────────────┐
│ Config Server │
└────────────────┘
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
spring:
application:
name: product-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
prefer-ip-address: true
Full Reference : See service-discovery.md for Eureka HA and Config Server.
spring:
cloud:
gateway:
routes:
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**
filters:
- StripPrefix=0
Full Reference : See gateway.md for custom filters and programmatic routes.
@Service
public class ProductClient {
@CircuitBreaker(name = "productService", fallbackMethod = "fallback")
@Retry(name = "productService")
public List<Product> getProducts() {
return restClient.get()
.uri("http://product-service/api/products")
.retrieve()
.body(new ParameterizedTypeReference<>() {});
}
private List<Product> fallback(Exception e) {
return List.of();
}
}
resilience4j:
circuitbreaker:
instances:
productService:
sliding-window-size: 10
failure-rate-threshold: 50
wait-duration-in-open-state: 10s
Full Reference : See resilience.md for Retry, Bulkhead, Rate Limiter, Feign.
@Service
@RequiredArgsConstructor
public class OrderService {
private final ProductClient productClient;
private final InventoryClient inventoryClient;
private final PaymentClient paymentClient;
@Transactional
public Order createOrder(CreateOrderRequest request) {
// 1. Verifica prodotti
List<Product> products = request.items().stream()
.map(item -> productClient.getProductById(item.productId()))
.toList();
// 2. Verifica inventario
boolean available = inventoryClient.checkAvailability(request.items());
if (!available) {
throw new InsufficientInventoryException("Items not available");
}
// 3. Crea ordine
Order order = Order.create(request.customerId(), products, request.items());
order = orderRepository.save(order);
// 4. Riserva inventario
inventoryClient.reserveItems(order.getId(), request.items());
// 5. Processa pagamento (con rollback)
try {
PaymentResult payment = paymentClient.processPayment(
new PaymentRequest(order.getId(), order.getTotal())
);
order.setPaymentId(payment.paymentId());
order.setStatus(OrderStatus.PAID);
} catch (PaymentFailedException e) {
inventoryClient.releaseReservation(order.getId());
order.setStatus(OrderStatus.PAYMENT_FAILED);
throw e;
}
return orderRepository.save(order);
}
}
@Configuration
public class LoadBalancerConfig {
@Bean
@LoadBalanced
public RestClient.Builder loadBalancedRestClientBuilder() {
return RestClient.builder();
}
}
// Usage: use service name instead of host
restClient.get()
.uri("http://product-service/api/products")
.retrieve()
.body(new ParameterizedTypeReference<>() {});
management:
tracing:
sampling:
probability: 1.0
zipkin:
tracing:
endpoint: http://localhost:9411/api/v2/spans
logging:
pattern:
level: "%5p [${spring.application.name:},%X{traceId:-},%X{spanId:-}]"
| Do | Don't |
|---|---|
| Use Service Discovery for all services | Hardcode service URLs |
| Implement Circuit Breaker with fallback | Ignore failures |
| Centralize config with Config Server | Duplicate configuration |
| Add distributed tracing | Miss observability |
| Use API Gateway as single entry point | Expose services directly |
| Error | Cause | Solution |
|---|---|---|
No instances available | Service not registered | Verify Eureka registration |
Connection refused | Service down | Implement Circuit Breaker |
Timeout | Service slow | Configure appropriate timeouts |
Config not loading | Config server unreachable | Use fail-fast: false or fallback |
| Load balancing not working |
| Anti-Pattern | Problem | Solution |
|---|---|---|
| Hardcoding service URLs | No discovery benefit | Use service names |
| No circuit breaker | Cascading failures | Add Resilience4j |
| Missing retry | Transient failures | Configure retry with backoff |
| No config refresh | Changes need redeploy | Use @RefreshScope |
| Synchronous everywhere | Tight coupling | Use async where appropriate |
| Problem | Diagnostic | Fix |
|---|---|---|
| Service not found | Check Eureka dashboard | Verify registration |
| Config not loading | Check config server logs | Verify path, profile |
| Circuit always open | Check failure threshold | Tune thresholds |
| Gateway routing fails | Check predicates | Verify route config |
| Load balancing not working | Check @LoadBalanced | Add annotation |
| File | Content |
|---|---|
| service-discovery.md | Eureka Server/Client, Config Server |
| gateway.md | API Gateway, Filters, Routes |
| resilience.md | Circuit Breaker, Retry, Feign, Testing |
Weekly Installs
1
Repository
First Seen
3 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
amp1
cline1
openclaw1
opencode1
cursor1
kimi-cli1
Supabase Postgres 最佳实践指南 - 8大类别性能优化规则与SQL示例
62,800 周安装
Docnify自动化:通过Rube MCP和Composio工具包实现文档操作自动化
1 周安装
Docmosis自动化集成指南:通过Rube MCP与Composio实现文档生成自动化
1 周安装
Dictionary API自动化教程:通过Rube MCP和Composio实现词典API操作自动化
1 周安装
detrack-automation:自动化追踪技能,集成Claude AI提升开发效率
1 周安装
Demio自动化工具包:通过Rube MCP和Composio实现Demio操作自动化
1 周安装
Deel自动化工具:通过Rube MCP与Composio实现HR与薪资操作自动化
1 周安装
| Missing @LoadBalanced |
| Annotate RestClient builder |