Spring-Cloud-hystrix-(容错机制)

Spring-cloud-hystrix-容错机制(当服务调用异常时进行响应)
1.在App.java中开启容错保护(加入此注解开启容错机制@EnableCircuitBreaker)
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class RequestApp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(RequestApp.class, args);
}

@Bean
@LoadBalanced
public RestTemplate newRestTemplate(){
return new RestTemplate();
}
}
2.pom.xml中引用hystrix依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.7.RELEASE</version>
</parent>
<dependencies>
<!-- 添加对Web的支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 要注册的需要引用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<!-- 容错保护机制 (调请求发生异常时进行处理) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
</dependencies>
<!--依赖管理,用于管理spring-cloud的依赖,其中Camden.SR3是版本号 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
3。Controller
@RequestMapping(value = "CircuitBreakerInfo")
public List<String> circuitBreakerInfo(){
return circuitBreakerserver.circuitBreakerInfoService();
}
Service
@HystrixCommand(fallbackMethod = "circuiterrorMethod")
public List<String> circuitBreakerInfoService(){
System.out.println("测试Hystrix / circuitBreaker 方法");
Map<String, Object> maps = new HashMap<String,Object>();
maps.put("name", "request");
return restTemplate.getForObject(ribbonUrl, List.class,maps);
}

猜你喜欢

转载自www.cnblogs.com/lvwqq/p/9006323.html