10 在Spring Cloud中使用Hystrix

  Hystrix主要用于保护调用服务的一方,如果被调用的服务发生故障,符合一定条件,就会开启断路器对调用的程序进行隔离。

1.准备测试程序

  在进行Spring Cloud整合Hystrix之前,我们先准备好测试程序。测试程序所用的项目如下:

  > hystrix-server:该项目作为Eureka服务器,端口为8761。

  > hystrix-provider: 该项目作为服务的提供者,这里只需要启动一个实例,端口为默认端口8080,提供person/{personId}服务,它根据personId的参数返回一个Penson实例,另外还会提供一个/hello服务,返回普通的字符串。

  > hystrix-invoker: 该项目作为服务调用者,使用的端口是9000。

  项目的目录结构如下

   

  本文主要会使用到hystrix-invoker项目来介绍如何在Spring Cloud中使用Hystrix,故下面会详细介绍hystrix-invoker项目,对于hystrix-server和 hystrix-provider这两个项目不会详细介绍。

2.Spring Cloud整合Hystrix

  为服务调用者(hystrix-invoker)项目添加相关的依赖(spring-cloud-starter-hystrix),pom.xml代码清单如下

  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.triheart</groupId>
    <artifactId>hystrixinvoker</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>1.5.3.RELEASE</version>
        </dependency>
    </dependencies>
</project>
View Code

  在服务调用者的应用启动类中,加入启动断路器的注解,应用启动类代码清单如下

  Invoker.java

package com.triheart.hystrixinvoker;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * @author 阿遠
 * Date: 2018/9/1
 * Time: 14:31
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class InvokerApp {

    @LoadBalanced
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

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

   新建服务类,在服务方法中调用服务,代码清单如下

  PersonService.java

package com.triheart.hystrixinvoker;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author 阿遠
 * Date: 2018/9/1
 * Time: 14:43
 */
@Service
public class PersonService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "getPersonFallback")
    public Person getPerson(Integer id) {
        // 使用RestTemplate调用Eureka服务
        Person person = restTemplate.getForObject("http://hystrix-privoder/person/{personId}", Person.class, id);
        return person;
    }

    /**
     * 定义回退方法
     * 主要这里传的参数与上面的一样,否则会报方法找不到的错误
     */
    public Person getPersonFallback(Integer id) {
        Person person = new Person();
        person.setId(0);
        person.setAge(21);
        person.setName("fallback");
        person.setMessage("request error");
        return person;
    }
}

  服务类中注入了RestTemplate,服务方法使用@HystrixCommand注解进行修饰,并且配置了回退方法。@HystrixCommand注解由Hystrix的javanica项目提供,该项目主要是为了简化Hystrix的使用。被@HstrixCommand修饰的方法,Hystrix会使用AspectJ对其进行代理,Spring会将相关的类转换成Bean放到容器中,在Spring Cloud中,我们无须过多关心Hystrix的命令管理。

  注意:此处的回退方法的参数需要与@HystrixCommand注解的方法一样,否则在后面调用该方法时会报如下错误

  接下来,编写控制器来调用服务类的方法,代码清单如下

  InvokerController.java

package com.triheart.hystrixinvoker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 阿遠
 * Date: 2018/9/1
 * Time: 14:53
 */
@RestController
@Configuration
public class InvokerController {

    @Autowired
    private PersonService personService;

    @RequestMapping(value = "/router/{personId}", method = RequestMethod.GET)
    public Person router(@PathVariable Integer personId) {
        Person person = personService.getPerson(personId);
        return person;
    }
}

  控制器比较简单,直接注入PersonService,然后调用方法即可。按照以下步骤启动集群:

  > 启动hystrix-server项目

  > 启动hystrix-provider项目

  > 启动hystrix-invoker项目

  打开浏览器,访问http://localhost:9000/router/0,输出如下

  接下来,我们停止hystrix-provider项目,再访问http://localhost:9000/router/0,输出如下

  可以看到,程序直接调用了回退的方法。

猜你喜欢

转载自www.cnblogs.com/a-yuan/p/9573501.html
今日推荐