千家信息网

Spring Cloud如何整合Hystrix

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,这篇文章给大家分享的是有关Spring Cloud如何整合Hystrix的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。19 Spring Cloud整合HystrixHys
千家信息网最后更新 2025年02月01日Spring Cloud如何整合Hystrix

这篇文章给大家分享的是有关Spring Cloud如何整合Hystrix的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

19 Spring Cloud整合Hystrix

Hystrix主要用于保护调用服务的一方,如果被调用的服务发生故障,符合一定条件,就开启断路器,对调用的程序进行隔离。在开始讲述本章的内容前,先准备测试项目,本章例子所使用的项目如下:

  • spring-hystrix-server:Eureka服务器,端口为8761,代码目录codes\06\6.4\spring-hystrix-server。

  • spring-hystrix-provider:服务提供者,本例只需要启动一个实例,端口为8080,默认提供"/person/{personId}"服务,根据personId参数返回一个Person实例,另外再提供一个"/hello"服务,返回普通的字符串。代码目录为codes\06\6.4\spring-hystrix-provider

  • spring-hystrix-invoker:服务调用者,9000端口,代码目录codes\06\6.4\spring-hystrix-invoker。

整合Hystrix

为服务调用者(spring-hystrix-invoker)项目添加依赖,添加后的依赖如下:

    org.springframework.cloud    spring-cloud-starter-config    org.springframework.cloud    spring-cloud-starter-eureka    org.springframework.cloud    spring-cloud-starter-ribbon    org.springframework.cloud    spring-cloud-starter-hystrix

在服务调用者的应用启动类中,加入启用断路器的注解,请见以下代码片断:

@SpringBootApplication@EnableDiscoveryClient@EnableCircuitBreakerpublic class InvokerApplication {    @LoadBalanced    @Bean    public RestTemplate getRestTemplate() {        return new RestTemplate();    }    public static void main(String[] args) {        SpringApplication.run(InvokerApplication.class, args);    }}

新建服务类,在服务方法中调用服务,请见代码清单6-17。

代码清单6-17:

codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\PersonService.java

@Componentpublic class PersonService {        @Autowired        private RestTemplate restTemplate;        @HystrixCommand(fallbackMethod = "getPersonFallback")        public Person getPerson(Integer id) {                // 使用RestTemplate调用Eureka服务                Person p = restTemplate.getForObject(                                "http://spring-hystrix-provider/person/{personId}",                                Person.class, id);                return p;        }        /**         * 回退方法,返回一个默认的Person         */        public Person getPersonFallback(Integer id) {                Person p = new Person();                p.setId(0);                p.setName("Crazyit");                p.setAge(-1);                p.setMessage("request error");                return p;        }}

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

接下来,编写控制器,调用服务类的方法,请见代码清单6-18。

代码清单6-18:

codes\06\6.4\spring-hystrix-invoker\src\main\java\org\crazyit\cloud\InvokerController.java

@RestController@Configurationpublic class InvokerController {        @Autowired        private PersonService personService;        @RequestMapping(value = "/router/{personId}", method = RequestMethod.GET,                         produces = MediaType.APPLICATION_JSON_VALUE)        public Person router(@PathVariable Integer personId) {                Person p = personService.getPerson(personId);                return p;        }}

控制器实现较为简单,直接注入PersonService,调用方法即可,按以下步骤启动集群:

  • 启动"spring-hystrix-server",本例中配置端口为8761。

  • 启动"spring-hystrix-provider",启动一个实例,端口为8080。

  • 启动"spring-hystrix-invoker",端口为9000。

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

{"id":1,"name":"Crazyit","age":33,"message":"http://localhost:8080/person/1"}

停止服务提供者(spring-hystrix-provide),即停止8080端口,再访问9000端口的地址,输出如下:

{"id":0,"name":"Crazyit","age":-1,"message":"request error"}

根据输出可知,由于调用失败,触发了回退方法。

命令配置

Spring Cloud中使用@HystrixCommand来声明一个命令,命令的相关配置,也可以在该注解中进行,以下的代码片断,配置了几个属性:

      /**         * 测试配置,对3个key进行命名         * 设置命令执行超时时间为1000毫秒         * 设置命令执行的线程池大小为1         */        @HystrixCommand(                        fallbackMethod="testConfigFallback", groupKey="MyGroup",                         commandKey="MyCommandKey", threadPoolKey="MyCommandPool",                         commandProperties={                                        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",                                                         value = "1000")                        },                         threadPoolProperties={                                        @HystrixProperty(name = "coreSize",                                                         value = "1")                        })

除了以上的几个配置外,@HystrixCommand注解还可以使用ignoreExceptions来处理异常的传播,请见以下代码片断:

 /**         * 声明了忽略MyException,如果方法抛出MyException,则不会触发回退         */        @HystrixCommand(ignoreExceptions = {MyException.class},                         fallbackMethod="testExceptionFallBack")        public String testException() {                throw new MyException();        }

Hystrix的命令、线程配置较多,由于篇幅所限,本小节仅简单地列举几个,读者可举一反三,按需要进行配置。

默认配置

对于一些默认的配置,例如命令组的key等,可以使用@DefaultProperties注解,这样就减少了@HystrixCommand注解的代码量。以下代码片断展示如何使用@DefaultProperties:

@DefaultProperties(groupKey="GroupPersonKey")public class PersonService {                @HystrixCommand // group key将使用"GroupPersonKey"        public String hello() {                return "";        }}

除了定义GroupKey外,还支持@HystrixCommand的其余配置,例如线程属性、命令属性等。

感谢各位的阅读!关于"Spring Cloud如何整合Hystrix"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

0