码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-03 09:56:46      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:object   break   sum   ipad   add   artifact   测试   man   str   

1、POM配置

  和普通Spring Boot工程相比,仅仅添加了Eureka、Ribbon、Hystrix、Spring Boot Starter Actuator依赖和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>
  <!-- 服务健康检测 -->
  <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 #应用名,请在hosts中添加映射
eureka:
  instance:
    hostname: ribbon-hello-service-consumer  #主机名
    preferIpAddress: true #使用IP注册
  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();
    }
}

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

标签:object   break   sum   ipad   add   artifact   测试   man   str   

原文地址:http://www.cnblogs.com/geniushuangxiao/p/7219505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!