负载均衡的实现原理在添加LoadBalanced注解后会启用拦截器对我们发起的服务调用请求进行拦截叫做LoadBalancerInterceptor,它实现ClientHttpRequestInterceptor接口。默认使用轮询的负载均衡策略也可以选择随机负载均衡策略如何修改负载均衡策略先创建随机分配策略的配置类不用加Configurationpublic class LoadBanancerConfig { // 将官方提供的RandomLoadBalancer注册为bean Bean public ReactorLoadBalancerServiceInstance randomLoadBalancer(Environment environment, LoadBalancerClientFactory clientFactory) { String name environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); return new RandomLoadBalancer(clientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),name); } }修改RestTemplate对应的配置类Configuration // 指定为user-service服务只要调用此服务就会使用我们指定的策略 //configuration LoadBanancerConfig.class 指定我们自定义的策略类 LoadBalancerClient(value user-service,configuration LoadBanancerConfig.class) public class BeanConfiguration { Bean // 负载均衡 LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }此时就完成了负载均衡策略的修改OpenFegin实现负载均衡Fegin和RestTemplate一样也是http客户端请求工具但是它的使用方式更加便捷。先加入依赖dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-openfeign/artifactId /dependency在启动类上加EnableFeignClients注解。SpringBootApplication EnableFeignClients public class AppBorrow { public static void main( String[] args ) { SpringApplication.run(AppBorrow.class, args); } }当我们要调用其他微服务的接口改怎么做呢先创建一个对应服务的接口类// 声明为user-service服务的客户端user-service表示服务名称 FeignClient(user-service) public interface UserClient { // 路径和参数保持一致 RequestMapping(/user/{uid}) User getUserById(PathVariable(uid) int uid); }实现具体业务Service public class BorrowServiceImpl implements BorrowService { Autowired private BorrowMapper borrowMapper; Autowired private RestTemplate restTemplate; Autowired private UserClient userClient; Autowired private BookClient bookClient; Override public BorrowDetail findBorrowById(int uid) { ListBorrow allByUid borrowMapper.getAllByUid(uid); // 获取用户信息 localhost:8101 改成服务名user-service /*User user restTemplate.getForObject(http://user-service/user/ uid, User.class); // 获取每本书的详细信息 ListBook bookList allByUid.stream().map(borrow - restTemplate.getForObject(http://book-service/book/ borrow.getBid(), Book.class)) .collect(Collectors.toList());*/ //使用openFeign User user userClient.getUserById(uid); // 获取每本书的详细信息 ListBook bookList allByUid.stream().map(borrow - bookClient.getBookById(borrow.getBid())) .collect(Collectors.toList()); return new BorrowDetail(user, bookList); } }Hystrix服务熔断思考以下场景服务A调用服务B服务B调用服务c服务c调用服务d。当服务d发生故障后会导致服务abc全部崩溃。当发生这种问题时要怎么解决?此时就需要Hystrix熔断器组件防止整条服务都崩溃了还有大量的请求不断访问。其工作机制由服务降级和服务熔断服务降级和服务熔断服务降级不会直接返回错误而是可以提供一个补救措施正常响应给请求者。这样相当于服务依然可用但是服务能力肯定下降了。服务熔断是在服务降级之后还是由大量的请求进来此时会直接返回备选结果不再执行正常方法当服务恢复后才会关闭熔断器。先导入Hystrix依赖由于springcloud中不再带有Hystrix所以要自己单独导入dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-hystrix/artifactId version2.2.10.RELEASE/version /dependency在启动类中添加注解EnableHystrix在Controller类中设置备选方案// 指定备选方案 HystrixCommand(fallbackMethod onError) RequestMapping(/borrow/{uid}) public BorrowDetail getBorrowById(PathVariable(uid) int id) { return borrowService.findBorrowById(id); } // 这个时备选方案 BorrowDetail onError(int id){ return new BorrowDetail(null, Collections.emptyList()); }注意Spring Boot3不支持Hystrix所以会发现不生效结论它能够对一段时间内出现的错误进行侦测当侦测到出错次数过多时熔断器会打开所有的请求直接响应失败这段时间内内执行一定数量的请求如果之后还是出现错误那么继续保持打开状态否则说明服务恢复正常熔断器关闭。OpenFeign实现降级Hystrix也可以配合Feign进行降级我们可以对接口中定义的远程调用单独进行降级操作。比如我们测试时关掉用户服务来测试服务降级实际上就是借阅服务调用用户服务失败才导致的降级。那么可以给远程调用添加一个替代方案比如远程调用失败直接上替代方案。具体的实现方案是创建一个feign客户端接口的实现类来替代原来的方案创建实现类Component public class UserFallbackClient implements UserClient { Override public User getUserById(int uid) { User user new User(); user.setName(我是补救方案); return user; } }在UserClient接口类中指定替代方案// 声明为user-service服务的客户端user-service表示服务名称 // fallback指定替代方案的实现类 FeignClient(value user-service,fallback UserFallbackClient.class) public interface UserClient { // 路径和参数保持一致 RequestMapping(/user/{uid}) User getUserById(PathVariable(uid) int uid); }在配置文件中开启熔断支持spring: cloud: openfeign: circuitbreaker: enabled: true这里就不用在controller类中使用HystrixCommand(fallbackMethod onError)注解了需要注释掉// 指定备选方案 // HystrixCommand(fallbackMethod onError) RequestMapping(/borrow/{uid}) public BorrowDetail getBorrowById(PathVariable(uid) int id) { return borrowService.findBorrowById(id); }这里需要注意由于我使用的是springcloud2025版本需要额外引入一个依赖才能实现openfeign降级。!-- Resilience4j 熔断器实现降级核心 -- dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-circuitbreaker-resilience4j/artifactId /dependency到此为止openfeign降级就实现了。监控页面部署除了对服务进行降级和熔断处理也可以对其进行实时监控只需安装监控页面即可具体步骤为创建一个新maven模块并引入依赖dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-netflix-hystrix-dashboard/artifactId version2.2.10.RELEASE/version /dependency添加配置文件server: port: 8900 hystrix: dashboard: #将localhost添加到白名单不然打不开本地页面 proxy-stream-allow-list: localhost创建启动类SpringBootApplication EnableHystrixDashboard public class AppHystrixDashboard { public static void main( String[] args ) { SpringApplication.run(AppHystrixDashboard.class, args); } }在需要监控的服务中添加Actuator依赖Actuator是spring boot程序的监控系统可以实现健康检查记录信息等只需要引入依赖并作简单配置即可。dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-actuator/artifactId /dependency在需要监控的服务中添加如下配置management: endpoints: web: exposure: include: *如果是springboot3.5.11 版本。官方已完全移除了hystrix依赖所以无法演示但是springboot2.x版本是正常支持的。管理页面的地址是http://localhost:8900/hystrix/在中间输入框填写具体要监控的服务地址比如http://localhost:8301/actuator/hystrix.stream 然后点击Monitor Stream即可进入监控页面。