Spring Cloud Ribbon 整合 Hystrix

在前面随笔 Spring Cloud 之 Ribbon 的ribbon工程基础上进行改造

1.pom.xml

加入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>

即pom.xml为

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dzpykj</groupId>
    <artifactId>ribbon</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>ribbon</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Edgware.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

2.application.yml文件配置不变

spring:
  application:
    name: ribbon
server:
  port: 8765
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

3.启动类加入@EnableCircuitBreaker注解开启Hystrix

package com.dzpykj;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //@EnableCircuitBreaker注解表明使用断路器
public class RibbonApplication {

    @Autowired
    private RestTemplateBuilder builder;

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return builder.build();
    }

//    @Bean
//    @LoadBalanced
//    RestTemplate restTemplate() {
//        return new RestTemplate();
//    }

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

4.新建HelloService类

重点是@HystrixCommand注解,fallbackMethod为异常时的回调方法

package com.dzpykj.hystrixService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@Service
public class HelloService {

    @Value("${server.port}")
    String port;

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "helloErrorFallBack")
    public String hello(String name) {
        return restTemplate.getForObject("http://eurekaclient/hi?name="+name, String.class);
    }

    public String helloErrorFallBack(String name) {
        return "Sorry "+name+",when you are visting ribbon project,port:"+port+",you meet an error";
    }
}

5.改造HelloController,调用HelloService的hello方法

package com.dzpykj.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.dzpykj.hystrixService.HelloService;

@RestController
public class HelloController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    HelloService helloService;

    @RequestMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return restTemplate.getForObject("http://eurekaclient/hi?name="+name, String.class);
    }

    @RequestMapping("/hi/{name}")
    public String hi(@PathVariable String name) {
        return helloService.hello(name);
    }
}

6.准备工作完成,开始测试.依次启动Eureka服务集群、Eureka单个客户端、Ribbon工程

6.1 按照Spring Cloud Eureka Server集群Demo级搭建的步骤启动Eureka服务peer1,peer2集群

6.2按照Spring Cloud Eureka服务Demo级搭建启动8763的Eureka客户端

6.3启动Ribbon工程

7.访问 http://localhost:8765/hi/chaixy

8.模拟eurekaclient服务异常:手动将eurekaclient服务关闭,再次访问 http://localhost:8765/hi/chaixy

可以看到,当eurekaclient服务关闭时,访问遇到异常,回调了异常时的回调方法helloErrorFallBack方法(HelloService类内的方法)

时间: 2024-07-29 21:18:24

Spring Cloud Ribbon 整合 Hystrix的相关文章

Spring Cloud Feign 整合 Hystrix

在前面随笔Spring Cloud 之 Feign的feign工程基础上进行改造 1.pom.xml依赖不变 2.application.yml文件添加feign.hystrix.enabled=true开启Hystrix断路器,即: spring: application: name: feign server: port: 8766 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ feign: hy

笔记:Spring Cloud Ribbon 客户端负载均衡

Spring Cloud Ribbon 是一个基于 HTTP 和 TCP 的客户端负载均衡工具,基于 Netflix Ribbon 实现,通过Spring Cloud 的封装,可以让我们轻松的将面向服务的REST 模板请求自动转换为客户端负载均衡的服务调用.客户端负载均衡在系统架构中是一个非常重要的,并且是不得不去实施的内容,因为负载均衡是对系统的高可用.网络压力的缓解和处理能力扩容的重要手段,客户端负载均衡需要通过心跳去维护服务端清单的健康性,这个需要服务注册中心配合完成,在Spring Cl

第四章 客户端负载均衡:Spring Cloud Ribbon

Spring Cloud R巾bon 是一个基于 HTTP 和 TCP 的客户端负载均衡工具,它基于 NetflixRibbon 实现. 通过 Spring Cloud 的封装, 可以让我们轻松地将面向服务的 REST 模板请求自动转换成客户端负载均衡的服务调用 客户端负载均衡 我们通常所说的负载均衡都指的是服务端负载均衡, 其中分为硬件负载均衡和软件负载均衡. 硬件负载均衡主要通过在服务器节点之间安装专门用于负载均衡的设备,比如 F5 等:而软件负载均衡则是通过在服务器上安装一些具有均衡负载功

spring cloud 学习(4) - hystrix 服务熔断处理

hystrix 是一个专用于服务熔断处理的开源项目,当依赖的服务方出现故障不可用时,hystrix有一个所谓的断路器,一但打开,就会直接拦截掉对故障服务的调用,从而防止故障进一步扩大(类似中电路中的跳闸,保护家用电器). 使用步骤:(仍然在之前的示例代码上加以改造) 一.添加hystrix依赖 compile 'org.springframework.cloud:spring-cloud-starter-hystrix' 二.在需要熔断的方法上添加注解 package com.cnblogs.y

笔记:Spring Cloud Ribbon 客户端配置详解

自动化配置 由于 Ribbon 中定义的每一个接口都有多种不同的策略实现,同时这些接口之间又有一定的依赖关系,Spring Cloud Ribbon 中的自动化配置能够很方便的自动化构建接口的具体实现,接口如下: IClientConfig:Ribbon 的客户端配置,默认采用 com.netflix.client.config.DefaultClientConfigImpl 实现. IRule:Ribbon 的负载均衡策略,默认采用 com.netflix.loadbalancer.ZoneA

Spring Cloud入门教程-Hystrix断路器实现容错和降级

简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products API来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务. 基础环境 JDK 1.8 Maven 3.3.9 IntelliJ 2018.1 Git 项目源码 Gitee码云 添加产品服务 在intelliJ中创建一个新的maven项目,

撸一撸Spring Cloud Ribbon的原理-负载均衡策略

在前两篇<撸一撸Spring Cloud Ribbon的原理>,<撸一撸Spring Cloud Ribbon的原理-负载均衡器>中,整理了Ribbon如何通过负载均衡拦截器植入RestTemplate,以及调用负载均衡器获取服务列表,如何过滤,如何更新等的处理过程. 因为,负载均衡器最终是调用负载均衡策略的choose方法来选择一个服务,所以这一篇,整理Ribbon的负载均衡策略. 策略类 RandomRule RoundRobinRule RetryRule WeightedR

spring cloud 入门系列八:使用spring cloud sleuth整合zipkin进行服务链路追踪

好久没有写博客了,主要是最近有些忙,今天忙里偷闲来一篇. =======我是华丽的分割线========== 微服务架构是一种分布式架构,微服务系统按照业务划分服务单元,一个微服务往往会有很多个服务单元,一个请求往往会有很多个单元参与,一旦请求出现异常,想要去定位问题点真心不容易,因此需要有个东西去跟踪请求链路,记录一个请求都调用了哪些服务单元,调用顺序是怎么样的以及在各个服务单元处理的时间长短.常见的服务链路追踪组件有google的dapper.twitter的zipkin.阿里的鹰眼等,它们

Spring Cloud Ribbon快速搭建

Spring Cloud Ribbon 是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现.通过 Spring Cloud 的封装, 可以让我们轻松地将面向服务的 REST 模板请求自动转换成客户端负载均衡的服务调用.在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的.Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign. 一般说的 负载均衡 是指 服务器端的