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

  • 相关阅读:
    ContentResolver.query()—>buildQueryString()
    maven基础依赖外部lib包(依赖钉钉sdk为例)
    在 Windows 中配置Maven
    windows系统下设置mtu值的方法
    dotfuscator 在混淆.Net Framework 4.0以上版本的时候报错的解决方法2
    dotfuscator 在混淆.Net Framework 4.0以上版本的时候报错的解决方法
    C# 反编译防范
    SpringBoot 集成Shiro
    windows系统下同时安装mysql5.5和8.0.11
    Eclipse安装STS(Spring Tool Suite (STS) for Eclipse)插件
  • 原文地址:https://www.cnblogs.com/jiefu/p/10056147.html
Copyright © 2011-2022 走看看