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

posted @ 2018-12-02 23:09  知识追求者  阅读(281)  评论(0编辑  收藏  举报