第五章:SpringCloudRibbon&Hystrix小实例

184 阅读1分钟

###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>