Spring Cloud Hystrix的使用
Spring Cloud Hystrix
在OpenFeign中使用Hystrix
模块1所需依赖:springweb
、eureka-client
、openfeign
模块2所需依赖:springweb
、eureka-client
模块依赖如上方所示,我就不示例创建项目了
编写(创建)方配置
yml:
server:
port: 8080
spring:
application:
name: rent-car-service
eureka:
client:
service-url:
defaultZone: eureka远程地址
instance:
hostname: localhost
instance-id: ${eureka.instance.hostname}:${spring.application.name}:${server.port}
启动类:
@SpringBootApplication
@EnableEurekaClient
编写方法
@RestController
public class RentCarController {
@GetMapping("rent")
public String rent(){
return "租车....";
}
}
上方就配置好了方法编写模块
调用(使用)方配置
yml:
server:
port: 8081
spring:
application:
name: customer-service
eureka:
client:
service-url:
defaultZone: eureka远程地址
instance:
hostname: localhost
instance-id: ${eureka.instance.hostname}:${spring.application.name}:${server.port}
feign:
hystrix:
enabled: true #在cloudF版前是默认开启的
启动类:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
编写Feign接口
@FeignClient(value = "rent-car-service")
public interface CustomerRentFeign {
@GetMapping("rent")
public String rent();
}
编写方法
@RestController
public class CustomerController {
@Autowired
private CustomerRentFeign customerRentFeign;
@GetMapping("customerRent")
public String CustomerRent(){
System.out.println("客户来了");
return customerRentFeign.rent();
}
}
这样即可实现调用编写方的接口了~
使用熔断器(Hystrix)
在调用方新增依赖
<!-- hystrix依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在feign
文件夹下创建hystrix
文件夹并编写文件CustomeRentFeignHystrix
@Component
public class CustomeRentFeignHystrix implements CustomerRentFeign {
@Override
public String rent() {
return "服务器雪崩备选方案~";
}
}
再在feign中指向备选方案
@FeignClient(value = "rent-car-service",fallback = CustomeRentFeignHystrix.class)
public interface CustomerRentFeign {
@GetMapping("rent")
public String rent();
}
这样即可实现即使服务挂了也不会报错,也能有备选方案~✌