0
点赞
收藏
分享

微信扫一扫

Spring Cloud Hystrix的使用

践行数据分析 2023-02-10 阅读 179

Spring Cloud Hystrix的使用

Spring Cloud Hystrix

在OpenFeign中使用Hystrix

模块1所需依赖:springwebeureka-clientopenfeign

模块2所需依赖:springwebeureka-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();
}

这样即可实现即使服务挂了也不会报错,也能有备选方案~✌

常用配置

在这里插入图片描述

举报

相关推荐

0 条评论