spring cloud Hystrix 服务容错保护(一)

主要处理某一服务故障,无法访问时,不用长久等待,给与错误反馈

1.启动之前的三个项目  消费者 注册中心 服务提供者

2.终端服务提供者,再次访问报错

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu Dec 21 14:38:09 CST 2017
There was an unexpected error (type=Internal Server Error, status=500).
I/O error on GET request for "http://hmq-demo-server/ceshi": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect

3.加入服务容错保护,在消费者项目(hmq-ribbon-server)中加入 Hysrix 依赖

<!--增加Hystrix依赖-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

4.主类(com.heimeiqiu.HmqDemoServerApplication)添加注解,开启断路器功能

@EnableCircuitBreaker

5.创建controller

package com.heimeiqiu.controller;

import com.heimeiqiu.service.HystirixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by wxl on 2017/12/21.
 */
@RestController
public class HystirixController {
    @Autowired
    HystirixService hystirixService;

    @RequestMapping(value = "/hystirix-server",method= RequestMethod.GET)
    public String helloConsumer(){
        return hystirixService.hystirixService();
    }
}
6.创建service

package com.heimeiqiu.service;

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;

/**
 * Created by wxl on 2017/12/21.
 */
@Service
public class HystirixService {
    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hystrirxBack")
    public String hystirixService(){
        return restTemplate.getForEntity("http://hmq-demo-server/ceshi",String.class).getBody();
    }

    public String hystrirxBack(){
        return "坏事了";
    }
}
7.这时候再将服务提供者,当机

显示 坏事了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值