• 断路器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,会调用断路器设置的回调方法

  • 相关阅读:
    引擎设计跟踪(一)
    Gamebyro 加入CEGUI
    开播庆祝
    引擎设计跟踪(八) Mile stone 2 准备中
    引擎设计跟踪(六)
    编辑器框架的思考
    地形法线贴图的优化
    引擎设计跟踪(五)
    引擎设计跟踪(九.2) 3DS MAX 导出插件 继续
    引擎设计跟踪(三)
  • 原文地址:https://www.cnblogs.com/jiefu/p/10056147.html
Copyright © 2020-2023  润新知