您的位置:首页 > 编程语言 > Java开发

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

2017-12-21 14:33 651 查看
主要处理某一服务故障,无法访问时,不用长久等待,给与错误反馈

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.这时候再将服务提供者,当机

显示 坏事了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐