熔断机制,指的是微服务架构中,由于某个服务瘫痪,为避免影响整个系统而采取的降级服务
简述:
由于网络或自身原因,服务不能确保一定可用。如果某个服务出现了问题,调用方的大量请求会使Servlet容器的线程资源被耗尽,导致服务瘫痪。而且这种故障会传播,进而威胁到这个微服务系统可用性
示例如下:基于springboot1.5.10
添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.10.RELEASE</version> </dependency> <!--Eureka 客户端--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>1.4.3.RELEASE</version> </dependency> <!--hystrix断路器--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> <version>1.4.3.RELEASE</version> </dependency>
application配置
server: port: 8901 #程序启动端口,也是Tomcat端口 spring: application: name: customer-order-hystrix #应用别名 eureka: client: service-url: defaultZone: http://user:123@localhost:10000/eureka instance: instance-id: ${spring.cloud.client.ipAddress}:${spring.application.name}:${spring.application.instance_id:${server.port}} prefer-ip-address: true
启动类
@SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker //启用熔断 public class CustomerHystrixApplication { @Bean public RestTemplate getTemp(){ return new RestTemplate(); } public static void main( String[] args ) { SpringApplication.run(CustomerHystrixApplication.class,args); System.out.println("customer start-up success"); } }
实体类
public class User { private Long id; private Date date; public User() { } public User(Long id) { this.id = id; this.date = new Date(); } public void setId(Long id) { this.id = id; } public void setDate(Date date) { this.date = date; } public Long getId() { return id; } public Date getDate() { return date; }
Controller
@RestController public class CustomeController { @Autowired private EurekaClient eurekaClient; @Autowired private RestTemplate restTemplate;//springboot提供的用于访问rest接口的对象 @GetMapping("/order/{id}") @HystrixCommand(fallbackMethod = "errora1") public User getOrder(@PathVariable Long id){ InstanceInfo instanceInfo = eurekaClient.getNextServerFromEureka("provider-user", false); String homePageUrl = instanceInfo.getHomePageUrl(); // 访问提供者,获取数据 User user = restTemplate.getForObject(homePageUrl+"/user/" + id,User.class);//通过访问rest获取json数据,然后转换成user对象 return user; } /** * 失败后执行的回调函数 * @param id * @return */ public User errora1(Long id) { User user = new User(); user.setId(-1000L); user.setDate(new Date()); return user; } }
注:回调函数和其使用者应返回相同的类型,这里省略了服务提供者模块 provider-user