当前位置: 代码迷 >> 综合 >> SpringCloud2.x搭建完整Demo(四) -集成Hystrix熔断机制
  详细解决方案

SpringCloud2.x搭建完整Demo(四) -集成Hystrix熔断机制

热度:99   发布时间:2023-10-28 10:15:50.0

SpringCloud2.x搭建完整Demo(四) -集成Hystrix熔断机制

1.服务提供方业务方法调用失败(熔断)

2.服务提供方服务调用不通(降级)

3.集成HystrixDashboard仪表盘

4.集成Turbine服务监控

---------------------------------------------------------------------------------------------------------------------------

1.服务提供方业务方法报错

1.1 【myspringcloud-provider-product】模块复制一份【myspringcloud-provider-product-hystrix】模块

1.2 【myspringcloud-provider-product-hystrix】模块添加POM依赖

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

1.3 【myspringcloud-provider-product-hystrix】模块ProductController修改

@RequestMapping(value="/getInfoById/{id}")@HystrixCommand(fallbackMethod = "getFallback")public Object get(@PathVariable("id") long id) {ProductPo product = iProductService.getInfoById(id);if(product == null) {throw new RuntimeException("该产品已下架!") ;}return product;
}public Object getFallback(@PathVariable("id") long id){ProductPo product = new ProductPo();product.setProductName("HystrixName");product.setProductDesc("HystrixDesc");product.setProductId(0L);return product;
}

1.4 【myspringcloud-provider-product-hystrix】模块修改启动类,增加熔断支持

@EnableCircuitBreaker

1.5 启动【myspringcloud-provider-product-hystrix】服务,查询一个数据库中不存在的ID,可以看到触发熔断

2.服务提供方服务器调用不通

2.1 【myspringcloud-service】模块新增一个fallback目录,新增一个IProductClientServiceFallbackFactory工厂类,用于失败调用(消费方降级处理)

package com.en.service.fallback;import com.en.po.ProductPo;
import com.en.service.IProductClientService;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;@Component
public class IProductClientServiceFallbackFactory implements FallbackFactory<IProductClientService> {@Overridepublic IProductClientService create(Throwable throwable) {return  new IProductClientService() {@Overridepublic ProductPo getProduct(long id) {ProductPo product = new ProductPo();product.setProductId(999999L);product.setProductName("feign-hystrixName");product.setProductDesc("feign-hystrixDesc");return  product;}@Overridepublic List<ProductPo> listProduct() {return null;}@Overridepublic boolean addPorduct(ProductPo product) {return false;}};}
}

2.2 【myspringcloud-service】模块修改IProductClientService,增加fallback配置

@FeignClient(name = "MYSPRINGCLOUD-PROVIDER-PRODUCT",configuration = FeignClientConfig.class,fallbackFactory = IProductClientServiceFallbackFactory.class)

2.3 【myspringcloud-consumer-feign】 修改application.yml配置文件,启用hystrix配置

feign:hystrix:enabled: true

2.4 启动注册中心、服务生产者、服务消费者

用消费者测试生产者服务:

关闭生产者服务,再次调用,前端也可正常访问

3.集成HystrixDashboard仪表盘

3.1 新建【microcloud-consumer-hystrix-dashboard】模块,并配置POM依赖

<?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"><parent><artifactId>myspringcloud</artifactId><groupId>com.en</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>myspringcloud-consumer-hystrix-dashboard</artifactId><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><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></dependencies>
</project>

 3.2 确保【microcloud-provider-product-hystrix】pom文件里有健康检查模块

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

 3.3 【microcloud-consumer-hystrix-dashboard】修改application.yml配置文件

server:port: 9001

3.4 【microcloud-consumer-hystrix-dashboard】模块创建启动类

package com.en.config;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;/*** @ClassName HystrixDashboardApp* @Description TODO* @Author liuxiaobai* @Date 2020/7/1 21:11* @Version 1.0**/
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApp {public static void main(String[] args) {SpringApplication.run(HystrixDashboardApp.class,args);}
}

 3.5 【microcloud-provider-product-hystrix】模块修改applcation.yml文件

management:endpoints:web:exposure:include: '*'

 3.6 启动【microcloud-provider-product-hystrix】模块,访问http://localhost:9001/hystrix

3.7 仪表盘模块页面填入连接:http://admin:root@localhost:8084/actuator/hystrix.stream,即可实现对8084服务的监控

4.集成Turbine服务监控

4.1  新建【myspringcloud-provider-user-hystrix】模块,用于仪表盘同时提供服务检测,POM如下

<?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"><parent><artifactId>myspringcloud</artifactId><groupId>com.en</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>myspringcloud-provider-user-hystrix</artifactId><dependencies><dependency><groupId>com.en</groupId><artifactId>myspringcloud-api</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-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId></dependency><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-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-hystrix</artifactId></dependency></dependencies>
</project>

4.2  【myspringcloud-api】模块新建VO、【myspringcloud-provider-user-hystrix】模块 Controller和启动类

package com.en.po;
import java.io.Serializable;public class Users implements Serializable {private String name;private int age;private String sex;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}
}
package com.en.controller;import com.en.po.Users;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/users")
public class UserController {@RequestMapping("/get/{name}")@HystrixCommandpublic  Object get(@PathVariable("name")String name) {Users users = new Users();users.setName(name);users.setAge(18);users.setSex("F");return users;}
}
package com.en;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication
@EnableCircuitBreaker
@EnableEurekaClient
public class UsersApp {public static void main(String[] args) {SpringApplication.run(UsersApp.class,args);}
}

4.3   修改【myspringcloud-provider-user-hystrix】模块配置文件

server:port: 8090spring:application:name: myspringcloud-provider-users-hystrixlogging:level:com.en.mapper: debugeureka:client: # 客户端进行Eureka注册的配置service-url:defaultZone: http://admin:root@eureka:7001/eureka,http://admin:root@eureka2:7002/eureka,http://admin:root@eureka3:7003/eurekainstance:instance-id: myspringcloud-provider-users-hystrixprefer-ip-address: truelease-renewal-interval-in-seconds: 2 # 设置心跳的时间间隔(默认是30秒)lease-expiration-duration-in-seconds: 5  # 如果现在超过了5秒的间隔(默认是90秒)info:app.name: myspringcloud-provider-users-hystrixcompany.name: enbuild.artifactId: $project.artifactId$build.modelVersion: $project.modelVersion$management:endpoints:web:exposure:include: '*'

4.4 新增【microcloud-consumer-turbine】模块,pom文件如下

<?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"><parent><artifactId>myspringcloud</artifactId><groupId>com.en</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>myspringcloud-consumer-turbine</artifactId><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-turbine</artifactId></dependency></dependencies></project>

4.5 【microcloud-consumer-turbine】模块配置文件

server:port: 9101
eureka:client:register-with-eureka: falseservice-url:defaultZone: http://admin:root@eureka:7001/eureka,http://admin:root@eureka2:7002/eureka,http://admin:root@eureka3:7003/eurekaturbine:app-config: MYSPRINGCLOUD-PROVIDER-PRODUCT-HYSTRIX,MYSPRINGCLOUD-PROVIDER-USERS-HYSTRIXcluster-name-expression: new String("default")

4.6  新建【microcloud-consumer-turbine】模块启动类

package com.en;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.turbine.EnableTurbine;@SpringBootApplication
@EnableTurbine
public class TurbineApp {public static void main(String[] args) {SpringApplication.run(TurbineApp.class,args);}
}

4.7 因为之前对【microcloud-provider-product-hystrix】模块进行了访问加密,所以需要设置放行方法,【mysrpingcloud-security】 修改WebSecurityConfiguration文件

package com.en.config;import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {@Overridepublic void configure(AuthenticationManagerBuilder auth)throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("USER").and().withUser("admin").password(new BCryptPasswordEncoder().encode("root")).roles("USER", "ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.httpBasic().and().authorizeRequests().anyRequest().fullyAuthenticated();http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);}@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/actuator/hystrix.stream","/turbine.stream") ;}}

4.8 启动注册中心、仪表盘、两个服务提供方、还有刚写的turbine模块。浏览器访问:http://localhost:9001/hystrix,输入监控地址http://localhost:9101/turbine.stream,分别多次调用服务提供方带有@HystrixCommand注解的方法:

http://localhost:8084/product/getInfoById/1

http://localhost:8090/users/get/enjoy

可以看到现在仪表盘可以对多个服务提供方进行监控

源码自取: 

https://github.com/L1021204735/myspringcloud4

 

  相关解决方案