Spring全家桶笔记十:服务调用与负载均衡
服务调用的演进
- 传统方式:直接通过HTTP或RPC调用
- 服务注册发现:Eureka、Nacos、Consul
- 负载均衡:Ribbon、LoadBalancer
- 服务网格:Istio、Envoy
RestTemplate服务调用
基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @RestTemplate @LoadBalanced public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
@Service public class OrderService { @Autowired private RestTemplate restTemplate; public Order getOrder(Long id) { String url = "http://user-service/user/" + id; return restTemplate.getForObject(url, Order.class); } }
|
拦截器实现认证
1 2 3 4 5 6 7 8 9 10 11 12
| public class AuthInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept( HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { request.getHeaders().add("Authorization", "Bearer token"); return execution.execute(request, body); } }
|
Feign服务调用
快速开始
1 2 3 4 5 6 7 8 9
| @FeignClient(name = "user-service") public interface UserClient { @GetMapping("/user/{id}") User getUserById(@PathVariable("id") Long id); @GetMapping("/user/list") List<User> getUsers(@RequestParam("ids") List<Long> ids); }
|
配置与优化
1 2 3 4 5 6 7
| @FeignClient( name = "user-service", url = "http://localhost:8080", configuration = FeignConfig.class, fallback = UserClientFallback.class ) public interface UserClient {}
|
1 2 3 4 5 6 7 8 9 10 11 12
| public class FeignConfig { @Bean public Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } @Bean public RequestInterceptor requestInterceptor() { return template -> template.header("X-Request-Id", UUID.randomUUID().toString()); } }
|
日志配置
1 2 3
| logging: level: com.example.client: DEBUG
|
负载均衡策略
常见策略
| 策略 |
说明 |
| RoundRobinRule |
轮询(默认) |
| RandomRule |
随机 |
| RetryRule |
重试 |
| WeightedResponseTimeRule |
响应时间加权 |
| BestAvailableRule |
最空闲服务器 |
| AvailabilityFilteringRule |
可用性过滤 |
自定义策略
1 2 3 4 5 6 7 8
| @Configuration public class MyRuleConfig { @Bean public IRule myRule() { return new MyCustomRule(); } }
|
负载均衡原理
- 服务注册:提供者向注册中心注册
- 服务发现:消费者从注册中心获取服务列表
- 负载均衡:根据策略选择服务实例
- 服务调用:发起HTTP请求
Nacos服务发现
服务注册
1 2 3 4 5 6 7
| spring: application: name: order-service cloud: nacos: discovery: server-addr: 127.0.0.1:8848
|
服务消费者
1 2 3 4 5
| @LoadBalanced @Bean public RestTemplate restTemplate() { return new RestTemplate(); }
|
服务元数据
1 2 3 4 5 6 7
| spring: cloud: nacos: discovery: metadata: version: v1 weight: 1.0
|
实际应用建议
- 优先使用Feign,代码更简洁
- 合理设置超时时间
- 配置合理的负载均衡策略
- 做好服务降级和熔断
- 使用Nacos进行服务治理
总结
Spring Cloud提供了完整的服务调用解决方案,从服务发现到负载均衡,配合Hystrix/Resilience4j实现服务容错,构建稳定的微服务架构。