本章注意讲解Hystrix断路器功能实现,该功能实现方式有ribbon和fegin两种,本章代码依赖前面章节实现。
1)ribbon方式实现Hystrix
步骤一:在xm-web-controller项目pom.xml文件中添加如下配置:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
步骤二:在xm-web-controller项目WebApplication类上添加@EnableHystrix注解,如图:
步骤三:修改xm-web-controller项目DemoServiceImpl接口实现类ribbonHello方法,代码如下:
@Override
@HystrixCommand(fallbackMethod = "hiError")
public String ribbonHello() {
return restTemplate.getForObject("http://module-oauth-server/demo/hello",String.class);
}
public String hiError() {
return "hi,sorry,error!";
}
步骤四:依次启动EurekaServerApplication、WebApplication、OAuthApplication模块
在浏览器中输入:http://localhost:8762/xm/demo/ribbon/hello,界面展示如下:
把OAuthApplication模块服务停止,再刷新地址访问,界面展示如下:
2)fegin方式实现Hystrix
步骤一:在module-oauth-resources项目下application.properties中添加以下配置:
说明:Feign是自带断路器的,在一些版本的Spring Cloud中,它没有默认打开。需要在配置文件中配置打开它。
feign.hystrix.enabled=true
步骤二:在module-oauth-api项目下新增一个DemoApiFallback.java,该类实现IDemoApi接口,代码如下:
package com.maven.xm.oauth.api.fallback;
import org.springframework.stereotype.Component;
import com.maven.xm.oauth.api.IDemoApi;
@Component
public class DemoApiFallback implements IDemoApi {
@Override
public String hello() {
return "sorry demo fallback!";
}
}
步骤三:修改module-oauth-api项目下IDemoApi接口类,新增fallback处理类,修改之后的代码如下:
package com.maven.xm.oauth.api;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.maven.xm.oauth.api.fallback.DemoApiFallback;
/**
* @FeignClient中value的名称要跟module-oauth-resources项目中application.properties文件的name保持一致
* @author Administrator
*
*/
@FeignClient(
value = "module-oauth-server",
fallback = DemoApiFallback.class
)
public interface IDemoApi {
@RequestMapping(value = "/demo/hello", method = RequestMethod.GET)
public String hello();
}
步骤四:依次启动EurekaServerApplication、WebApplication、OAuthApplication模块
在浏览器中输入:http://localhost:8762/xm/demo/fegin/hello,界面展示如下:
把OAuthApplication模块服务停止,再刷新地址访问,界面展示如下:
本章功能已实现完,待续!
源码下载地址: https://gitee.com/ouyangjun_xm/springcloud/attach_files下chapter-four.rar压缩包
码云账户: oyj812438109@163.com 密码: oyj812438109@163.com
请勿恶意操作,谢谢!
本文说明:该文章属于原创,如需转载,请标明文章转载来源