服务降级的配置,一般倾向于放在客户端,具体看业务需求
1. 服务降级
https://github.com/Netflix/hystrix/wiki
1.1 配置 Hystrix 服务,为模拟降级的环境作准备
1.1.1 服务端用eureka 集群,参照其他配置
1.1.2 provider端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- spring cloud eureka server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
server:
port: 8001
spring:
application:
name: cloud-provider-hystrix-payment
eureka:
client:
register-with-eureka: true # false: 不把 eureka 自身注册在注册中心里面, 不作高可用的情况下使用这个
fetch-registry: true # false: 不从 eureka 上获取服务的注册信息
service-url:
# defaultZone: http://127.0.0.1:7001/eureka/ # 单例版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
主启动类:
package com.pyh.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class PaymentMainHystrix8001 {
public static void main(String[] args) {
SpringApplication.run(PaymentMainHystrix8001.class,args);
}
}
Service
package com.pyh.springcloud.service.impl;
import com.pyh.springcloud.service.PaymentService;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class PaymentServiceImpl implements PaymentService {
/**
* 正常访问的方法
*/
public String PaymentInfo_OK(Integer id){
return "线程池: " + Thread.currentThread().getName()+" PaymentInfo_OK " + id + " 正常!";
}
/**
* 程序异常、超时、服务熔断、线程池信号量打满,都会造成服务降级
*/
public String PaymentInfo_FAIL(Integer id){
int timer = 3;
try {
TimeUnit.SECONDS.sleep(timer);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: " + Thread.currentThread().getName()+" PaymentInfo_TIMEOUT " + id + " 耗时"+timer+"秒";
}
}
Controller
package com.pyh.springcloud.controller;
import com.pyh.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
public class PaymentController {
@Resource
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@GetMapping("/payment/hystrix/ok/{id}")
public String PaymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentService.PaymentInfo_OK(id);
log.info("PaymentOK 结果:"+result);
return result;
}
@GetMapping("/payment/hystrix/timeout/{id}")
public String PaymentInfo_FAIL(@PathVariable("id") Integer id){
String result = paymentService.PaymentInfo_FAIL(id);
log.info("PaymentFAIL 结果:"+result);
return result;
}
}
1.1.3 consumer端,使用feign 调用服务,引入 Hystrix
pom.xml 主要依赖
<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.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
server:
port: 808
spring:
application:
name: cloud-consumerfeign-hystrix-order
eureka:
client:
register-with-eureka: false # false:不把 eureka 自身注册在注册中心里面, 不作高可用的情况下使用这个
fetch-registry: true # false:不从 eureka 上获取服务的注册信息
service-url:
# defaultZone: http://127.0.0.1:7001/eureka/ # 单例版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
feign:
client:
config:
default: # feign 全局日志 # cloud-payment-service: #也可以指定某个 feign 服务名称
connectTimeout: 5000
readTimeout: 5000
loggerLevel: FULL # 日志级别 FULL / headers / basic / none 默认
主启动类:
package com.spring.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableFeignClients
public class OrderHystrixMain808 {
public static void main(String[] args) {
SpringApplication.run(OrderHystrixMain808.class, args);
}
}
Service类:
package com.spring.springcloud.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "cloud-provider-hystrix-payment")
public interface PaymentHystrixService {
@GetMapping("/payment/hystrix/ok/{id}")
public String PaymentInfo_OK(@PathVariable("id") Integer id);
@GetMapping("/payment/hystrix/timeout/{id}")
public String PaymentInfo_FAIL(@PathVariable("id") Integer id);
}
Controller类:
package com.spring.springcloud.controller;
import com.spring.springcloud.service.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
public class OrderHystrixController {
@Resource
PaymentHystrixService paymentHystrixService;
@GetMapping("/consumer/payment/hystrix/ok/{id}")
public String PaymentInfo_OK(@PathVariable("id") Integer id){
String result = paymentHystrixService.PaymentInfo_OK(id);
log.info("PaymentOK 结果:"+result);
return result;
}
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
public String PaymentInfo_FAIL(@PathVariable("id") Integer id){
String result = paymentHystrixService.PaymentInfo_FAIL(id);
log.info("PaymentFAIL 结果:"+result);
return result;
}
}
1.2 Provider端 服务降级配置
1.2.1 主启动类 添加 @SpringCloudApplication
//@EnableCircuitBreaker // SpringCloudApplication 已包括这个注解
@SpringCloudApplication
1.2.2 service 类
在原方法上面添加注解和配置服务降级的触发条件,并指定服务降级时的兜底方法
/**
* 程序异常、超时、服务熔断、线程池信号量打满,都会造成服务降级
*/
@HystrixCommand(fallbackMethod = "PaymentInfo_TimeoutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
})
public String PaymentInfo_FAIL(Integer id){
int timer = 3;
// int aget = 10/0; //用于测试程序出问题的情况
try {
TimeUnit.SECONDS.sleep(timer);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "线程池: " + Thread.currentThread().getName()+" PaymentInfo_TIMEOUT " + id + " 耗时"+timer+"秒";
}
public String PaymentInfo_TimeoutHandler(Integer id){
return "线程池: " + Thread.currentThread().getName()+" 系统繁忙,请稍后再试 /(ㄒoㄒ)/~~" ;
}
1.3 Consumer 端 服务降级配置
yaml 中不要开启hystrix, 否则默认的1秒超时会覆盖掉controller的配置
feign:
hystrix:
enabled: false
主启动类:添加 @EnableHystrix
@EnableHystrix
public class OrderHystrixMain808 {
controller: 添加服务降级处理
@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "PaymentInfo_TimeoutHandler", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
})
public String PaymentInfo_FAIL(@PathVariable("id") Integer id){
String result = paymentHystrixService.PaymentInfo_FAIL(id);
log.info("PaymentFAIL 结果:"+result);
return result;
}
public String PaymentInfo_TimeoutHandler(Integer id){
return " 系统繁忙,请稍后再试 /(ㄒoㄒ)/~~,端口号:" + serverPort ;
}
此处有坑,需要重新配置ribbon和hystrix的默认超时时间
ribbon:
# 指的是建立连接后, 从服务端读取到可用资源所用的时间
ReadTimeout: 15000
# 建立连接所允许的最大时间,适用于网络正常情况下,两端连接所用时间
ConnectionTimeout: 3000
hystrix:
command:
default: #default全局有效,service id指定应用有效
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 20000 #断路器超时时间,默认1000ms
1.4 配置全局服务降级方法
打开全局默认配置:
hystrix:
command:
default: #default全局有效,service id指定应用有效
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 20000 #断路器超时时间,默认1000ms
在controller添加注解
@DefaultProperties(defaultFallback = "payment_Global_FallbackHandler")
public class OrderHystrixController
在controller下的方法添加注解:
@HystrixCommand
public String PaymentInfo_FAIL(@PathVariable("id") Integer id){xxxx}
1.5 解决代码通配的耦合度高的问题
feign:
hystrix:
enabled: true
添加一个类实现Hystrix接口类
package com.spring.springcloud.service.impl;
import com.spring.springcloud.service.PaymentHystrixService;
import org.springframework.stereotype.Service;
@Service
public class PaymentHystrixServiceFallbackImpl implements PaymentHystrixService {
@Override
public String PaymentInfo_OK(Integer id) {
return "PaymentHystrixServiceFallbackImpl...PaymentInfo_OK";
}
@Override
public String PaymentInfo_FAIL(Integer id) {
return "PaymentHystrixServiceFallbackImpl...PaymentInfo_FAIL";
}
}
接口类中添加参数 fallback = PaymentHystrixServiceFallbackImpl.class
@FeignClient(value = "cloud-provider-hystrix-payment"
,fallback = PaymentHystrixServiceFallbackImpl.class)
public interface PaymentHystrixService
2.服务熔断
熔断机制的注解是 @HystrixCommand
大神理论:https://martinfowler.com/bliki/CircuitBreaker.html
payment端配置案例:在service 和 controller 添加方法,controller调用service所配置的带有服务熔断配置的方法
========服务熔断
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
// 在 10,000 毫秒时间以内,在必须超过10 次或以上的请求中,如果失败率高于 60%,即10次有6次或者以上失败次数, 那么开启断路器
@HystrixProperty(name = "circuitBreaker.enabled",value = "true") // 是否开启断路器
,@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10") // 请求次数,在窗口期内,请求次数必须大于给定的值,才有资格打开断路器
,@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000") // 时间窗口期
,@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60") // 失败率达到多少后跳闸
})
@Override
public String paymentCircuitBreaker(Integer id){
if(id<0){
throw new RuntimeException("**** id 不能为负数");
}
String seralNumber = IdUtil.simpleUUID();
return Thread.currentThread().getName() + "\t" + " 调用成功,流水号:" + seralNumber;
}
public String paymentCircuitBreaker_fallback(Integer id){
return "id 不能为负数,请稍后再试! /(ㄒoㄒ)/~~ id:"+id;
}
========服务熔断
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
String result = paymentService.paymentCircuitBreaker(id);
log.info("paymentCircuitBreaker 结果:"+result);
return result;
}
2.2 配置全局熔断:
添加兜底方法
在服务类中配置兜底的方法和熔断机制
在需要监控的方法上添加 @HystricCommand
@Service
@DefaultProperties(defaultFallback = "globalCircuitBreaker_fallback", commandProperties = {
@HystrixProperty(name = "circuitBreaker.enabled",value = "true") // 是否开启断路器
,@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10") // 请求次数,在窗口期内,请求次数必须大于给定的值,才有资格打开断路器
,@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000") // 时间窗口期
,@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "40") // 失败率达到多少后跳闸
})
public class PaymentServiceImpl implements PaymentService {
// 服务熔断
/**
* 正常访问的方法
*/
@Override
@HystrixCommand
public String PaymentInfo_OK(Integer id){
if(id<0){
throw new RuntimeException("**** id 不能为负数");
}
return "线程池: " + Thread.currentThread().getName()+" PaymentInfo_OK " + id + " 正常!";
}
public String globalCircuitBreaker_fallback(){
return " 全局熔断触发.....";
}
}
3. dashboard 监控
3.1 dashboard端
必要 pom 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<!-- feign相关 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
server:
port: 9001
hytrix dashboard 启动类
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardMain9001.class,args);
}
}
3.2 需要被监控的eureka服务器或服务集群,如payment 端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- spring cloud eureka server-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management:
endpoints:
enabled-by-default: true # 默认开启所有监控端点信息 true
web:
exposure:
include: "*" #以web方式暴露所有端点
endpoint: # 具体端点的配置
health:
show-details: always # 显示Health端点的详细信息
enabled: true
info:
enabled: true
metrics:
enabled: true
beans:
enabled: true
注意:新版本Hystrix需要在被监控端主启动PaymentMainHystrix8001中指定监控路径
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream"); // "/actuator/hystrix.stream"
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}