本文共 3159 字,大约阅读时间需要 10 分钟。
微服务架构的核心特点之一是多服务、多数据源的支持,这种架构模式使得各个服务之间形成了紧密的依赖关系。然而,这种依赖关系也带来了潜在的风险。一旦某个微服务出现故障,可能会引发连锁反应,导致整个系统陷入瘫痪,这就是著名的“雪崩效应”。为了应对这一挑战,微服务架构引入了熔断器这一重要的容错机制。
在微服务架构中,当一个服务出现故障时,熔断器会介入切断相关服务的调用,向客户端返回预定义的错误信息或占位响应,从而避免因单个服务故障导致整个系统的崩溃。熔断器的作用可以分为以下几个阶段:
熔断器在检测到依赖服务恢复后,会自动重新建立连接,确保服务依赖关系的稳定性。
在高并发场景下,服务器资源可能面临巨大的压力。服务降级是一种有效的资源管理策略,通过关闭非核心服务或限制不必要的功能,释放服务器资源,确保核心业务的正常运行。服务降级可以根据具体业务需求和流量情况灵活配置,例如在双十一大促销期间,支付宝会对部分非核心服务进行降级,以保障核心交易的顺畅进行。
在实际项目中,Hystrix作为熔断器的一重要组成部分,通过以下核心依赖实现服务熔断和降级功能:
org.springframework.cloud spring-cloud-starter-hystrix
在配置Hystrix时,常用的注解包括:
以下是基于Ribbon和Feign的服务熔断案例:
public String getDefaultInfo() { return "服务被熔断";} @RequestMapping("/showInfo1")@HystrixCommand(fallbackMethod = "getDefaultInfo")public String showInfo1() { return restTemplate.getForObject(server_name + "/getInfo", String.class);} @RequestMapping("/showInfo2")@HystrixCommand( fallbackMethod = "getDefaultInfo", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000"), @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "1000") }, threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "20"), @HystrixProperty(name = "maxQueueSize", value = "-1") }, ignoreExceptions = {ServiceException.class})public String showInfo2() { String value = ""; if (value.equals("")) { throw new ServiceException("运行异常"); } return restTemplate.getForObject(server_name + "/getInfo", String.class);} @SpringBootApplication(scanBasePackages = {"cloud.node02.consume", "cloud.block.code.service"})@EnableEurekaClient@EnableDiscoveryClient@EnableFeignClients(basePackages = {"cloud.block.code.service"})public class Application_8002 { public static void main(String[] args) { SpringApplication.run(Application_8002.class, args); }} @FeignClient(value = "NODE02-PROVIDER", fallback = FallbackService.class)public interface GetAuthorService { @RequestMapping(value = "/getAuthorInfo/{authorId}", method = RequestMethod.GET) String getAuthorInfo(@PathVariable("authorId") String authorId);} @Componentpublic class FallbackService implements GetAuthorService { @Override public String getAuthorInfo(String authorId) { return "服务被熔断" + authorId; }} feign: hystrix: enabled: true
@SpringBootApplication(scanBasePackages = {"cloud.node02.consume", "cloud.block.code.service"})@EnableEurekaClient@EnableDiscoveryClient@EnableFeignClients(basePackages = {"cloud.block.code.service"})public class Application_8002 { public static void main(String[] args) { SpringApplication.run(Application_8002.class, args); }} 转载地址:http://mnqkz.baihongyu.com/