Hystrix 服务熔断

书籍,人,借阅服务之间相互调用, 高度耦合, 一旦一个服务故障, 其他服务会雪崩, 和多米诺骨牌一样

Hystrix 服务熔断_第1张图片

Hystrix

熔断器, 保险丝

服务降级

提供补救措施发给请求者, 服务可用, 能力下降了

borrow-service 导入依赖

   <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
             <version>2.2.10.RELEASEversion>
    dependency>
@SpringBootApplication
@EnableHystrix   //启用Hystrix
public class BorrowApplication {
    public static void main(String[] args) {
        SpringApplication.run(BorrowApplication.class, args);
    }
}
@RestController
public class BorrowController {

    @Resource
    BorrowService service;

    @HystrixCommand(fallbackMethod = "onError")    //使用@HystrixCommand来指定备选方案
    @RequestMapping("/borrow/{uid}")
    UserBorrowDetail findUserBorrows(@PathVariable("uid") int uid){
        return service.getUserBorrowDetailByUid(uid);
    }
        
      //备选方案,这里直接返回空列表了
      //注意参数和返回值要和上面的一致
    UserBorrowDetail onError(int uid){
        return new UserBorrowDetail(null, Collections.emptyList());
    }
}

关闭user-service, 运行备选方案

服务熔断

Hystrix 服务熔断_第2张图片

OpenFeign 降级

Hystrix 配合 Feign降级

定义UserFallbackClient类实现接口

@Component   //注意,需要将其注册为Bean,Feign才能自动注入
public class UserFallbackClient implements UserClient{
    @Override
    public User getUserById(int uid) {   //这里我们自行对其进行实现,并返回我们的替代方案
        User user = new User();
        user.setName("我是替代方案");
        return user;
    }
}

UserClient指定fallback

@FeignClient(value = "user-service", fallback = UserFallbackClient.class)
public interface UserClient {

    //路径保证和其他微服务提供的一致即可
    @RequestMapping("/user/{uid}")
    User getUserById(@PathVariable("uid") int uid);  //参数和返回值也保持一致
}

配置文件开启熔断支持

feign:
  circuitbreaker:
    enabled: true

+++

部署监控页面

创建新项目

<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboardartifactId>
    <version>2.2.10.RELEASEversion>
dependency>
server:
  port: 8900
hystrix:
  dashboard:
    # 将localhost添加到白名单,默认是不允许的
    proxy-stream-allow-list: "localhost"

主类加注解 @EnableHystrixDashboard

@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashBoardApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashBoardApplication.class, args);
    }
}

需要监控的服务添加actuator[译:监视器]依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-actuatorartifactId>
dependency>

borrow-service项目加yml配置

management:
  endpoints:
    web:
      exposure:
        include: '*'

测试

http://localhost:8301/actuator/hystrix.stream

Hystrix 服务熔断_第3张图片

访问borrow book user的接口

Hystrix 服务熔断_第4张图片

1/actuator/hystrix.stream

[外链图片转存中…(img-K21HSCdU-1685256322228)]

访问borrow book user的接口

[外链图片转存中…(img-Hz4QgofV-1685256322229)]

你可能感兴趣的:(hystrix,java,spring)