003客户端负载均衡Ribbon & 短路器Hystrix

1、POM配置

  和普通Spring Boot工程相比,仅仅添加了Eureka、Ribbon、Hystrix依赖和Spring Cloud依赖管理

<dependencies>
  <!--添加Eureka Server依赖-->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <!-- 负载均衡ribbon -->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
  </dependency>
  <!-- 断路器Hystrix -->
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
  </dependency>
  <!-- 服务健康检查,必须添加,否则此服务不会启动hystrix.stream -->   <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-actuator</artifactId>   </dependency> </dependencies> <dependencyManagement>   <dependencies>     <!--Spring Cloud依赖版本管理-->     <dependency>       <groupId>org.springframework.cloud</groupId>       <artifactId>spring-cloud-dependencies</artifactId>       <version>Dalston.SR1</version>       <type>pom</type>       <scope>import</scope>     </dependency>   </dependencies> </dependencyManagement>

02、使能Eureka Client

@SpringBootApplication
@EnableEurekaClient  //使能Eureka客户端
@EnableCircuitBreaker  //使能断路器
public class RibbonApplication {
    @Bean
    @LoadBalanced  //负载均衡的RestTemplate
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

03、src/main/resources工程配置文件application.yml

server:
  port: 3001  #默认启动端口
spring:
  application:
    name: ribbon-hello-service-consumer #应用名
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1000/eureka/ #服务注册中心地址

04、负载均衡消费

@Service
public class HelloConsumerService {
    @Autowired
    private RestTemplate restTemplate;

    // 负载均衡消费
    @HystrixCommand(fallbackMethod = "fallback")
    public String hello() {
        return this.restTemplate.getForObject("http://hello-service-provider/hello/", String.class);
    }
    //短路器打开时,执行此函数
    public String fallback() {
        return "Error";
    }
}

05、测试使用服务

@RestController
public class HelloController {
    @Autowired
    private HelloConsumerService helloService;

    @GetMapping("/hello")
    public String hello() {
        return this.helloService.hello();
    }
}
原文地址:https://www.cnblogs.com/geniushuangxiao/p/7219505.html