Skip to content

spring cloud 学习笔记0x4 #21

Description

@hugeterry

熔断器Hystrix

ribbon+Hystrix

  • 使用笔记0x2的eurekaribbon工程,在pom中增加hystrix的起步依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
  • 在application启动类中添加@ EnableHystrix,开启Hystrix
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class EurekaribbonApplication {

    public static void main(String[] args) {
        SpringApplication.run(EurekaribbonApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • 改造RibbonService,加上@HystrixCommand,创建熔断器
@Service
public class RibbonService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "errorService")
    public String niceService(String name) {
        return restTemplate.getForObject("http://EUREKACLIENT/nice?name=" + name, String.class);
    }

    public String errorService(String name) {
        return "sorry," + name;
    }
}

注解HystrixCommand指定fallbackMethod熔断方法,熔断方法返回抱歉提示的字符串

feign+Hystrix

  • 使用笔记0x3的eurekafeign工程,在配置文件中开启熔断器
    feign.hystrix.enabled=true

    feign本身含有熔断器,D版本后默认没有打开

  • 对InvokeService进行改造在@ FeignClient注解中加入fallback的指定类

@FeignClient(value = "eurekaclient", fallback = InvokeServiceHystric.class)
public interface InvokeService {
    @RequestMapping(value = "/nice", method = RequestMethod.GET)
    String sayService(@RequestParam(value = "name") String name);
}
  • InvokeServiceHystric需要实现InvokeService,并注入到ioc中
@Component
public class InvokeServiceHystric implements InvokeService {
    @Override
    public String sayService(String name) {
        return "sorry," + name;
    }
}
  • 启动eurekafeign服务,打开http://localhost:8665/feign?name=hugeterry ,会正确显示8662,8664的端口返回报文,将8662,8664进程关闭,此时熔断器响应,看到返回如下报文:
    sorry,hugeterry

命令

  • 查看端口进程命令 lsof -i:-P
    P为端口号例如:lsof -i:4200
  • 关闭进程命令 kill -9 [pid]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions