第八章 SpringCloud之Feign、Hystrix结合使用
#这个章节主要是针对Hystrix的使用,因为Feign的章节在上一节已经实现了,整个代码也是在上一个章节的基础上修改的
##################Hystrix一个简单Demo实现#######################
1、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.test</groupId>
<artifactId>eureka-client-feign-hystrix</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>eureka-client-feign-hystrix</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
2、application.yml文件配置
spring:
application:
name: eureka-client-feign-hystrix #应用名
logging: #logging日志配置
level:
root: INFO
org.hibernate: INFO
server:
port: 8667 #服务端口 eureka:
instance:
hostname: localhost
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:8661/eureka
3、启动类加配置
package com.test.eurekaclientfeign; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class EurekaClientFeignHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientFeignHystrixApplication.class, args);
} }
4、User.java类
package com.test.eurekaclientfeign.entity; import java.io.Serializable;
import java.math.BigDecimal; public class User implements Serializable {
private Long id; private String name; private String username; private BigDecimal balance; private short age; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public BigDecimal getBalance() {
return balance;
} public void setBalance(BigDecimal balance) {
this.balance = balance;
} public short getAge() {
return age;
} public void setAge(short age) {
this.age = age;
}
}
5、自定义UserFeignClientConfig.java类,该类的使用,表示不使用Feign的默认配置
package com.test.eurekaclientfeign.feign; import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class UserFeignClientConfig {
/* @Bean
public Contract feignContract() {
return new feign.Contract.Default();
}*/ @Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
6、UserFeignClient1.java
package com.test.eurekaclientfeign.feign; import com.test.eurekaclientfeign.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @FeignClient(name = "eureka-client-user", configuration = UserFeignClientConfig.class)
public interface UserFeignClient1 {
@RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
User findById(@PathVariable("id") Long id);
}
7、MovieController.java类,实现远程调用的类
package com.test.eurekaclientfeign.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.test.eurekaclientfeign.entity.User;
import com.test.eurekaclientfeign.feign.UserFeignClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; @RestController
public class MovieController { @Autowired(required = true)
private UserFeignClient1 userFeignClient1; @GetMapping(value = "/hystrix/{id}")
@HystrixCommand(fallbackMethod = "defaultMethod")
//一但无法调用远程的findById(),则会调用Hystrix的默认接口defaultMethod(),其参数要一致,否则无法使用
public User findById(@PathVariable("id") Long id) {
return this.userFeignClient1.findById(id);
} public User defaultMethod(@PathVariable("id") Long id){
User user = new User();
user.setId(id);
user.setName("hystrix");
return user;
} }
8、URL访问
http://localhost:8661/ # 服务发现
http://192.168.137.1:8667/hystrix/9 #实现断路,因为数据库没有id=9的数据
http://192.168.137.1:8667/hystrix/1 #可以正常访问
Hystrix访问实现如下:

########Hystrix将调用访问和断路执行方法绑定在一个线程#########
只需在MovieController.java中的HystrixCommand添加一个commandProperties属性即可,如下
package com.test.eurekaclientfeign.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.test.eurekaclientfeign.entity.User;
import com.test.eurekaclientfeign.feign.UserFeignClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController; @RestController
public class MovieController { @Autowired(required = true)
private UserFeignClient1 userFeignClient1; @GetMapping(value = "/hystrix/{id}")
@HystrixCommand(fallbackMethod = "defaultMethod",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
//一但无法调用远程的findById(),则会调用Hystrix的默认接口defaultMethod(),其参数要一致,否则无法使用
//添加commandProperties属性,可以使得findById()和defaultMethod()绑定到一个线程中
public User findById(@PathVariable("id") Long id) {
return this.userFeignClient1.findById(id);
} public User defaultMethod(@PathVariable("id") Long id){
User user = new User();
user.setId(id);
user.setName("hystrix");
return user;
} }
###########Hystrix健康检查与监控################
1、在pom.xml再添加下面依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、在启动类添加一个Bean
package com.test.eurekaclientfeign; import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean; @SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class EurekaClientFeignHystrixApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientFeignHystrixApplication.class, args);
} @Bean
public ServletRegistrationBean getServlet(){
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/actuator/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
3、启动Eureka和服务程序,访问远程调用的服务程序,执行下面的URL
#使用了actuator,所以都必须以这个组件开始
http://localhost:8667/actuator/hystrix.stream http://localhost:8667/actuator/health
第八章 SpringCloud之Feign、Hystrix结合使用的更多相关文章
- springcloud(七) feign + Hystrix 整合 、
之前几章演示的熔断,降级 都是 RestTemplate + Ribbon 和 RestTemplate + Hystrix ,但是在实际开发并不是这样,实际开发中都是 Feign 远程接口调用. ...
- SpringCloud 在Feign上使用Hystrix(断路由)
SpringCloud 在Feign上使用Hystrix(断路由) 第一步:由于Feign的起步依赖中已经引入了Hystrix的依赖,所以只需要开启Hystrix的功能,在properties文件中 ...
- springcloud(九)-Feign使用Hystrix
前言 上一篇我们使用注解@HystrixCommond的fallbackMethod属性实现回退.然而,Feign是以接口形式工作的,它没有方法体,上一篇讲解的方式显然不适用于Feign. 那么Fei ...
- SpringCloud中使用Hystrix
1. 引言 一般而言,一个服务都是部署了多台机器的,那么在这种情况下,当其中一个服务挂了以后Hystrix是怎么处理的呢? 为了验证这个问题,我们准备两个服务:user-api 和 app-gate ...
- 二、springcloud之熔断器hystrix
一.背景 雪崩效应 在微服务架构中通常会有多个服务层调用,基础服务的故障可能会导致级联故障,进而造成整个系统不可用的情况,这种现象被称为服务雪崩效应.服务雪崩效应是一种因“服务提供者”的不可用导致“服 ...
- SpringCloud 进阶之Hystrix(断路器)
1. Hystrix 断路器 Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败, 比如超时,异常等,Hystrix能够保证在一个依赖出问题的情况 ...
- SpringCloud之Feign
[前面的话]书接上文,本文的某些知识依赖我的第一篇SpringCLoud的文章:SpringCloud之Eureka,如果没有看过可以先移步去看一下.另外在微服务架构中,业务都会被拆分成一个个独立的服 ...
- SpringCloud系列-整合Hystrix的两种方式
Hystrix [hɪst'rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力.本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力. 本文目录 一.H ...
- springcloud之Feign、ribbon设置超时时间和重试机制的总结
一 超时时间配置 如果在一个微服务当中对同一个接口同时配置了Hystrix与ribbon两个超时时间,则在接口调用的时候,两个计时器会同时读秒. 比如,访问一个接口需要2秒,你的ribbon配置的超时 ...
随机推荐
- signal,blinker:信号(看我脸色行事)
signal 什么是信号(signal)? 信号在linux中被用来进行进程间的通信和异步处理,简单地可以理解会为回调函数,当发送一个信号时,会触发相应的操作.python中的signal模块便是用来 ...
- 最完美ThinkPHP Nginx 配置文件
一个配置文件,完美支持普通,兼容,pathinfo,rewrite4种url模式,别怪我没提醒你收藏哦. 常见的静态文件404时也不会再去跑一遍fastcgi浪费资源. server { listen ...
- Zen Cart 常用SQL命令
网店日常维护过程中,难免要跟各种批量操作打交道, 虽然大多数操作可以通过批量上传 (easy populate) 和 快速更新 模块来完成, 但在应用便捷性和一些功能性的调整上, 总有一定的局限性; ...
- 仿响应式html:JS来判断页面是在手机端还是在PC端打开的方法
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/a419419/article/detail ...
- MySQL更新字段来自另一个表的count()值
假设有文章post和评论comment两个表,文章表记录有评论的数量,但是这个值我们要一次更新. 如下,现在post表的comment_count都是0,我们的目标是:执行一个SQL语句,让其把统计c ...
- Codeforces Round #593 (Div. 2) D. Alice and the Doll
题目:http://codeforces.com/problemset/problem/1236/D思路:机器人只能按照→↓←↑这个规律移动,所以在当前方向能够前进的最远处即为界限,到达最远处右转,并 ...
- mongodb 3.0 WT 引擎性能测试(转载)
网上转载来的测试,仅供参考.原文地址:http://www.mongoing.com/benchmark_3_0 类机器. 测试均在单机器,单实例的情况下进行. 机器A(cache 12G,即内存&g ...
- thinkPHP5.0.22初体验---request相关用法
如果浏览器要返回美观排列的json数据,可以安装火狐浏览器的插件 返回XML的数据格式 渲染模板的用法 return $this->fetch('index/index2')效果 扒掉stirp ...
- 1223 drf引入以及restful规范
目录 前后台的数据交互 drf 知识点概括 1. 框架安装 2. 接口 2.1 什么是接口 2.2 接口文档 2.3 接口工具的使用 2.4 restful接口规范 debug的使用 前后台的数据交互 ...
- Spring MVC 面试题
什么是springMVC?作用? springMVC是一种web层mvc框架,用于替代servlet(处理|响应请求,获取表单参数,表单校验等). 为什么要用springMVC? 基本上,框架的作用就 ...