1.什么是Hystrix
Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败
2.熔断器的工作机制
3.hytrix的入门demo
3.1pom文件
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
</dependencies>
3.2application.yml
server:
port: 8200
spring:
application:
name: springcloud-consumer-hy
eureka:
client:
serviceUrl:
defaultZone: http://user:123@localhost:10000/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找
3.3启动类
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class HyonsumerApplication {
public static void main(String[] args) {
SpringApplication.run(HyonsumerApplication.class,args);
}
}
3.4修改消费者
import carry.shuai.pojo.User;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class UserControllerConsoumer {
@Autowired
private RestTemplate restTemplate;
@Autowired
private EurekaClient eurekaClient;
@GetMapping("/getUser")
@HystrixCommand(fallbackMethod = "shibai")
public User getUser(){
String url = eurekaClient.getNextServerFromEureka("springcloud-privider", false).getHomePageUrl();
// String url = "192.168.247.1:8001/";
//url.replace("/","%2F");
System.out.println("url:"+url+"getUserById");
//User user = restTemplate.getForObject(url + "getUserById", User.class);
//System.out.println("user:"+user);
return restTemplate.getForObject(url+"getUserById",User.class);
}
//失败后调用的方法
public User shibai(){//参数需要和原方法一致
User user = new User();
user.setId(-400L);
user.setName("jeery");
return user;
}
}
4.设置hytrix的超时时长
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMillisecond: 6000 # 设置hystrix的超时时间为6000ms
5.别的springcloud组件
1.eureake:https://blog.csdn.net/oldshaui/article/details/86589606
2.ribbon :https://blog.csdn.net/oldshaui/article/details/86593504