多语言展示
当前在线:1977今日阅读:11今日分享:15

如何实现SpringCloud服务熔断

如何实现SpringCloud服务熔断
工具/原料
1

SpringCloud

2

intellij idea

方法/步骤
1

服务熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务不可用或者相应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回“错误”的相应信息。当检测到改节点微服务调用响应正常后恢复调用链路。在springcloud框架里熔断机制通过hystrix实现。hystrix会监控微服务之间调用的状况,当失败的调用到一定阀值,缺省是5秒内20次调用失败就会启动熔断机制。熔断机制的注解是@HystrixCommand。新建项目模块microcloudservice-provider-dept-hystrix-8001。

2

在项目中添加hystrix相关的依赖maven坐标。            microservicecloud        com.gwolf.springcloud        1.0-SNAPSHOT        4.0.0    com.gwolf.springcloud    microcloudservice-provider-dept-hystrix-8001    microcloudservice-provider-dept-hystrix-8001    http://www.example.com            UTF-8        1.8        1.8                            com.gwolf.springcloud            microcloudservice-api            ${project.version}                                    junit            junit            4.11            test                            mysql            mysql-connector-java                            com.alibaba            druid                            org.mybatis.spring.boot            mybatis-spring-boot-starter                            org.springframework.cloud            spring-cloud-starter-eureka                            org.springframework.cloud            spring-cloud-starter-config                            org.springframework.boot            spring-boot-starter-actuator                            ch.qos.logback            logback-core                            org.springframework.boot            spring-boot-starter-jetty                            org.springframework.boot            spring-boot-starter-web                            org.springframework.cloud            spring-cloud-starter-hystrix                            org.springframework.boot            spring-boot-starter-test                            org.springframework            springloaded                            org.springframework.boot            spring-boot-devtools                                                                        maven-clean-plugin                    3.0.0                                                                    maven-resources-plugin                    3.0.2                                                    maven-compiler-plugin                    3.7.0                                                    maven-surefire-plugin                    2.20.1                                                    maven-jar-plugin                    3.0.2                                                    maven-install-plugin                    2.5.2                                                    maven-deploy-plugin                    2.8.2                                       

3

修改项目application.yml文件。server:  port: 8001mybatis:  config-location: classpath:mybatis/mybatis.cfg.xml    # mybatis配置文件所在路径  type-aliases-package: com.gwolf.springcloud.entities       # 定义所有操作类的别名所在包  mapper-locations:                                     # 所有的mapper映射文件  - classpath:mybatis/mapper/**/*.xmlspring:  datasource:    type: com.alibaba.druid.pool.DruidDataSource    # 配置当前要使用的数据源的操作类型    driver-class-name: com.mysql.cj.jdbc.Driver      # 配置MySQL的驱动程序类    url: jdbc:mysql://localhost:3306/cloudDB01?serverTimezone=UTC   # 数据库连接地址    username: root                                  # 数据库用户名    password: root                            # 数据库连接密码    dbcp2:                                          # 进行数据库连接池的配置      min-idle: 5                                   # 数据库连接池的最小维持连接数      initial-size: 5                               # 初始化提供的连接数      max-total: 5                                  # 最大的连接数      max-wait-millis: 200                          # 等待连接获取的最大超时时间  application:    name: microcloudservice-provider-dept    eureka:  client:    service-url:       defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  instance:    instance-id: microcloudservice-provider-dept-hystrix-8001    prefer-ip-address: true  info:  app.name: gwolf-microcloudservice-provider-dept-8001  company.name: www.gwolf.com  build.artifactId: $project.artifactId$  build.version:  $project.version$

4

修改控制层DeptHystrixController,增加熔断机制注解。一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的方法。package com.gwolf.springcloud.controller;import com.gwolf.springcloud.entities.Dept;import com.gwolf.springcloud.service.DeptService;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;import java.util.List;@RestControllerpublic class DeptHystrixController {    @Resource    private DeptService deptService;                @RequestMapping(value = '/dept/get/{id}',method = RequestMethod.GET)    @HystrixCommand(fallbackMethod = 'processHystrix_get')    public Dept get(@PathVariable('id') long id) {        Dept dept = this.deptService.get(id);        if(null == dept) {            throw  new RuntimeException('该ID:' + id + '没有对应的信息');        }        return dept;    }          public Dept processHystrix_get(@PathVariable('id') long id) {        Dept dept = new Dept();        dept.setDeptno((int)id);        dept.setDname('该ID:' + id + '没有对应的信息');        dept.setDb_source('no data in this database');                return dept;    }}

5

修改主启动类Dept_Hystrix_8001_StartSpringCloudApplication并添加新注解@EnableCircuitBreaker。package com.gwolf.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@EnableEurekaClient@EnableDiscoveryClient@EnableCircuitBreakerpublic class Dept_Hystrix_8001_StartSpringCloudApplication {    public static void  main(String[] args) {        SpringApplication.run(Dept_Hystrix_8001_StartSpringCloudApplication.class,args);    }}

6

启动相应的微服务来测试我们的熔断机制。

推荐信息