在父工程基础上建立Hystrix子工程,创建服务提供者
springcloud-consumer-dept-hystrix
通用的方式把springcloud-provider-dept-8081服务方的pom.xml文件,以及配置文件yml复制过来
通常使用新功能,
1:导入依赖pom,
2:编写配置文件yml,
server:port: 8081#mybatis配置mybatis:type-aliases-package: org.springcloud.pojoconfig-location: classpath:mybatis/mybatis-config.xmlmapper-locations: classpath:mybatis/mapper/*.xml#开启自动驼峰命名# configuration:# map-underscore-to-camel-case:#spring配置spring:application:name: springcloud-provider-dept-hystrix #修改applicationname为hystrixdatasource:# 数据库名称type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/db03?useUncode=true&characterEncoding=utf8&verifyServerCertificate=false&useSSL=false&allowMultiQueries=trueusername: rootpassword: root#eureka 的配置eureka:client:service-url:# 服务注册到哪里 打开eureka服务配置以配置中的地址为准# eureka配置好之后,开启eureka功能注解defaultZone: http://eureka7001.com:7001/eureka,http://eureka7001.com:7002/eureka,http://eureka7001.com:7003/eurekainstance:# 修改eureka——Status up 描述# instance-id: provider-dept-8081instance-id: ${spring.application.name}:${server.port}prefer-ip-address: true# actuator 监控配置info:app.name: provider-deptcompany.name: blog.junjay.com# 服务开发者名称(作者)author: junjay
3:开启注解enable*主启动类 ,或controller
package org.springcloud.controller;import org.springcloud.pojo.Dept;import org.springcloud.service.DeptService;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;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;/*** @author My 提供RestFul 风格服务*/@RestControllerpublic class DeptController {@Autowiredprivate DeptService deptService;// 使用@HystrixCommand 设置fallbackMethod当出现失败调用方法回调hystrixGet方法@GetMapping("/dept/queryById/{deptno}")@HystrixCommand(fallbackMethod = "hystrixGet")public Dept queryById(@PathVariable("deptno") Long deptno) {Dept dept = deptService.queryById(deptno);// 添加实际业务逻辑,如果查询id为空,则抛出异常if (dept == null) {throw new RuntimeException("id=》" + deptno + ",不存在该条信息,或查找不到~~");}return dept;}@GetMapping("/dept/queryById1/{deptno}")public Dept queryById1(@PathVariable("deptno") Long deptno) {return deptService.queryById(deptno);}// 备选方案,熔断public Dept hystrixGet(@PathVariable("deptno") Long deptno) {return new Dept().setDeptno(deptno).setDname("id=》" + deptno + ",没有对于信息,null----@hystrix").setDb_source(" 没有 这个数据库 ");}}
@HystrixCommand 注解
1 Execution:用来控制HystrixCommand.run()的执行
execution.isolation.strategy:该属性用来设置HystrixCommand.run()执行的隔离策略。默认为THREAD。
execution.isolation.thread.timeoutInMilliseconds:该属性用来配置HystrixCommand执行的超时时间,单位为毫秒。
execution.timeout.enabled:该属性用来配置HystrixCommand.run()的执行是否启用超时时间。默认为true。
execution.isolation.thread.interruptOnTimeout:该属性用来配置当HystrixCommand.run()执行超时的时候是否要它中断。
execution.isolation.thread.interruptOnCancel:该属性用来配置当HystrixCommand.run()执行取消时是否要它中断。
execution.isolation.semaphore.maxConcurrentRequests:当HystrixCommand命令的隔离策略使用信号量时,该属性用来配置信号量的大小。当最大并发请求达到该设置值时,后续的请求将被拒绝。
2 Fallback:用来控制HystrixCommand.getFallback()的执行
fallback.isolation.semaphore.maxConcurrentRequests:该属性用来设置从调用线程中允许HystrixCommand.getFallback()方法执行的最大并发请求数。当达到最大并发请求时,后续的请求将会被拒绝并抛出异常。
fallback.enabled:该属性用来设置服务降级策略是否启用,默认是true。如果设置为false,当请求失败或者拒绝发生时,将不会调用HystrixCommand.getFallback()来执行服务降级逻辑。
3 Circuit Breaker:用来控制HystrixCircuitBreaker的行为。
circuitBreaker.enabled:确定当服务请求命令失败时,是否使用断路器来跟踪其健康指标和熔断请求。默认为true。
circuitBreaker.requestVolumeThreshold:用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为20的时候,如果滚动时间窗(默认10秒)内仅收到19个请求,即使这19个请求都失败了,断路器也不会打开。
circuitBreaker.sleepWindowInMilliseconds:用来设置当断路器打开之后的休眠时间窗。休眠时间窗结束之后,会将断路器设置为“半开”状态,尝试熔断的请求命令,如果依然时候就将断路器继续设置为“打开”状态,如果成功,就设置为“关闭”状态。
circuitBreaker.errorThresholdPercentage:该属性用来设置断路器打开的错误百分比条件。默认值为50,表示在滚动时间窗中,在请求值超过requestVolumeThreshold阈值的前提下,如果错误请求数百分比超过50,就把断路器设置为“打开”状态,否则就设置为“关闭”状态。
circuitBreaker.forceOpen:该属性默认为false。如果该属性设置为true,断路器将强制进入“打开”状态,它会拒绝所有请求。该属性优于forceClosed属性。
circuitBreaker.forceClosed:该属性默认为false。如果该属性设置为true,断路器强制进入“关闭”状态,它会接收所有请求。如果forceOpen属性为true,该属性不生效。
4 Metrics:该属性与HystrixCommand和HystrixObservableCommand执行种捕获的指标相关。
metrics.rollingStats.timeInMilliseconds:该属性用来设置滚动时间窗的长度,单位为毫秒。该时间用于断路器判断健康度时需要收集信息的持续时间。断路器在收集指标信息时会根据设置的时间窗长度拆分成多个桶来累计各度量值,每个桶记录了一段时间的采集指标。例如,当为默认值10000毫秒时,断路器默认将其分成10个桶,每个桶记录1000毫秒内的指标信息。
metrics.rollingStats.numBuckets:用来设置滚动时间窗统计指标信息时划分“桶”的数量。默认值为10。
metrics.rollingPercentile.enabled:用来设置对命令执行延迟是否使用百分位数来跟踪和计算。默认为true,如果设置为false,那么所有的概要统计都将返回-1。
metrics.rollingPercentile.timeInMilliseconds:用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
metrics.rollingPercentile.numBuckets:用来设置百分位统计滚动窗口中使用桶的数量。
metrics.rollingPercentile.bucketSize:用来设置每个“桶”中保留的最大执行数。
metrics.healthSnapshot.intervalInMilliseconds:用来设置采集影响断路器状态的健康快照的间隔等待时间。
5 Request Context:涉及HystrixCommand使用HystrixRequestContext的设置。
requestCache.enabled:用来配置是否开启请求缓存。
requestLog.enabled:用来设置HystrixCommand的执行和事件是否打印到日志的HystrixRequestLog中。
[
](https://blog.csdn.net/chengqiuming/article/details/81568234)
/*** Copyright 2012 Netflix, Inc.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package com.netflix.hystrix.contrib.javanica.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/*** This annotation used to specify some methods which should be processes as hystrix commands.*/@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface HystrixCommand {/*** The command group key is used for grouping together commands such as for reporting,* alerting, dashboards or team/library ownership.* <p/>* default => the runtime class name of annotated method** @return group key*/String groupKey() default "";/*** Hystrix command key.* <p/>* default => the name of annotated method. for example:* <code>* ...* @HystrixCommand* public User getUserById(...)* ...* the command name will be: 'getUserById'* </code>** @return command key*/String commandKey() default "";/*** The thread-pool key is used to represent a* HystrixThreadPool for monitoring, metrics publishing, caching and other such uses.** @return thread pool key*/String threadPoolKey() default "";/*** Specifies a method to process fallback logic.* A fallback method should be defined in the same class where is HystrixCommand.* Also a fallback method should have same signature to a method which was invoked as hystrix command.* for example:* <code>* @HystrixCommand(fallbackMethod = "getByIdFallback")* public String getById(String id) {...}** private String getByIdFallback(String id) {...}* </code>* Also a fallback method can be annotated with {@link HystrixCommand}* <p/>* default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}** @return method name*/String fallbackMethod() default "";/*** Specifies command properties.** @return command properties*/HystrixProperty[] commandProperties() default {};/*** Specifies thread pool properties.** @return thread pool properties*/HystrixProperty[] threadPoolProperties() default {};/*** Defines exceptions which should be ignored.* Optionally these can be wrapped in HystrixRuntimeException if raiseHystrixExceptions contains RUNTIME_EXCEPTION.** @return exceptions to ignore*/Class<? extends Throwable>[] ignoreExceptions() default {};/*** Specifies the mode that should be used to execute hystrix observable command.* For more information see {@link ObservableExecutionMode}.** @return observable execution mode*/ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;/*** When includes RUNTIME_EXCEPTION, any exceptions that are not ignored are wrapped in HystrixRuntimeException.** @return exceptions to wrap*/HystrixException[] raiseHystrixExceptions() default {};/*** Specifies default fallback method for the command. If both {@link #fallbackMethod} and {@link #defaultFallback}* methods are specified then specific one is used.* note: default fallback method cannot have parameters, return type should be compatible with command return type.** @return the name of default fallback method*/String defaultFallback() default "";}
DeptProviderHystrix_8081 主启动类开启hystrix注解
package org.springcloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;// 启动类@SpringBootApplication// 开启eureka 在服务启动后自动将服务注册到eureka中@EnableEurekaClient// 服务发现及DeptController中的discovery方法@EnableDiscoveryClient// 添加对熔断的支持//Enable 启用 ,Circuit- 电路,Breaker 断路器@EnableCircuitBreakerpublic class DeptProviderHystrix_8081 {public static void main(String[] args) {SpringApplication.run(DeptProviderHystrix_8081.class, args);}}
启动服务访问
如果访问数据库中没有的信息,模拟异常,查看结果
隐藏eureka中的地址端口
prefer-ip-address: true #以IP地址注册到服务中心,相互注册使用IP地址

