第五章:SpringCloudRibbon&Hystrix小实例

1.添加pom

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

2.启动类上添加注解

@EnableCircuitBreaker
附图:

image.png

3.在@RequestMapping上添加注解@HystrixCommand(fallbackMethod = "findByIdFallback")

附图:


image.png

源码:

package com.fantj.fantjconsumermovieribbon.controller;

import com.fantj.fantjconsumermovieribbon.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
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;

/**
 * Created by Fant.J.
 * 2017/11/11 17:43
 */
@RestController
public class MovieController {
    @Autowired
    private RestTemplate template;

@HystrixCommand(fallbackMethod = "findByIdFallback")
@RequestMapping("/movie/{id}")
public User findById(@PathVariable Long id){
        return this.template.getForObject("http://provider-user3/simple/"+id,User.class);
    }

    public User findByIdFallback(Long id){
        User user = new User();
        user.setId(id);
        return user;
    }
}

其中,fallbackMethod = "findByIdFallback"表示断路器启用后调用findByIdFallback方法。
从代码中可以看出,我在这里是通过ribbon访问provider-user3/simple/"+id这个服务内容,如果正常访问的话,会调用provider-user3服务中的/simple/"+id方法。
eureka:

image.png

1. 访问provider-user3/:
image.png
2. 访问hystrix:
image.png
3. 然后我停止provider-user3/服务:
image.png
4. 最后访问hystrix:
image.png

说明我们的hystrix起到了作用。(调用了fallback方法)

小知识点

访问hystrix服务下的 /health 可以查看健康启动状况.

image.png

  • 我在这里开启eureka、provider-user3/、Hystrix 三个服务,请求hystrix的health


    image.png
  • 然后我关掉provider-user3服务,再请求/health


    image.png

    说明了hystrix已启用。

 "hystrix": {
    "status": "CIRCUIT_OPEN",
    "openCircuitBreakers": Array[1][
      "MovieController::findById"           //说明断路器回调到MovieController的findById方法。
    ]
  }

image.png

还有/hystrix.stream监控信息(不用,会被dashboard代替)
image.png

注意
/health 必须要有actuator的依赖支持

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 你我曾经无话不谈 可是现在 是什么改变了我们 你说,你会一直陪着我直到老 为何现在变成了沉默无言 发出去的每句话都...
    千层云林阅读 313评论 5 29
  • 晨行 躲了一切去晨行 不带任何行李 自己的心也是最轻 慢步游走摇曳在风中 失重的灵魂和枯叶轻歌慢舞 目光搁浅在雾中...
    山雨来时阅读 269评论 0 0
  • 什么时候爱上写作的呢?我常常会问自己。是高中时写过的征文登上《汉江浪》的时候吗?是大学时写过的文章拿到“读书观影”...
    Ann安墨染阅读 357评论 1 2