第五章:SpringCloudRibbon&Hystrix小实例

###1.添加pom

        <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>
复制代码

###2.启动类上添加注解 @EnableCircuitBreaker 附图:

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

源码:

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:

######1. 访问provider-user3/:

######2. 访问hystrix:

######3. 然后我停止provider-user3/服务:

######4. 最后访问hystrix:

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

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

  • 我在这里开启eureka、provider-user3/、Hystrix 三个服务,请求hystrix的health
  • 然后我关掉provider-user3服务,再请求/health
    说明了hystrix已启用。
 "hystrix": {
    "status": "CIRCUIT_OPEN",
    "openCircuitBreakers": Array[1][
      "MovieController::findById"           //说明断路器回调到MovieController的findById方法。
    ]
  }
复制代码

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

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

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值