zoukankan      html  css  js  c++  java
  • 断路器Ribbon

    断路器:就是对服务访问不到的情况做出自己的错误,也就是故障转移(将当前出现故障的请求重新返回特定消息)

    改造消费者项目(RibbonDemo)

    1、在pom.xml中引入hystrix的jar包

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>

    2、在RibbonApp类开启断路器(@EnableHystrix)

    package com.cppdy;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalanced;
    import org.springframework.cloud.netflix.hystrix.EnableHystrix;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    //开启断路器
    @EnableHystrix
    public class RibbonApp {
    
        public static void main(String[] args) {
            SpringApplication.run(RibbonApp.class, args);
        }
    
        @Bean
        @LoadBalanced
        RestTemplate template() {
    
            return new RestTemplate();
        }
    
    }

    3、在HelloService类注入断路器(@HystrixCommand(fallbackMethod = "helloError"))

    package com.cppdy.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.client.RestTemplate;
    
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    
    @Service
    public class HelloService {
    
        @Autowired
        private RestTemplate template;
    
        @HystrixCommand(fallbackMethod = "helloError")
        public String hellService(String name) {
    
            return template.getForObject("http://CPPDY-HELLO/hello?name" + name, String.class);
        }
    
        // 断路时的回调方法
        public String helloError(String name) {
    
            return "Service Error:" + name;
        }
    
    }

    4、先启动EurekaDemo(注册中心项目),再启动RibbonDemo(消费者项目)端口号设置为9003,访问http://localhost:9003/hello,会调用断路器设置的回调方法

  • 相关阅读:
    【BZOJ1452】【JSOI2009】count
    【BZOJ1030】【JSOI2007】文本生成器
    【BZOJ2427】【HAOI2010】软件安装
    从【BZOJ4173】谈做题技巧
    小A的旅行(绿豆蛙的归宿)【期望DP】
    甜点 【多重背包】
    洛谷 [P1154] 奶牛分厩
    POJ [P2631] Roads in the North
    洛谷 [P3258] 松鼠的新家
    洛谷 [P3398] 仓鼠找sugar
  • 原文地址:https://www.cnblogs.com/jiefu/p/10056147.html
Copyright © 2011-2022 走看看