首页 > 其他分享 >Hystrix + OpenFeign+ SpringCloud +Nacos

Hystrix + OpenFeign+ SpringCloud +Nacos

时间:2023-02-16 14:35:55浏览次数:51  
标签:OpenFeign Hystrix SpringCloud boot value HystrixProperty spring id name

 

 

注意:

2023年2月  spring cloud 最新版本不支持nacos 2.2 和hystrix,测试发现以下这个版本还支持

          <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8 </version> 

 

当前使用的环境是: :: Spring Boot ::        (v2.2.2.RELEASE)

 

安装nacos

home (nacos.io)

Linux centOS 7 安装

关闭防火墙

systemctl stop firewalld 或 systemctl disable firewalld

安装 Nancos

unzip nacos-server-2.2.0.zip -d /opt/module/

启动nacos

[root@machine137 nacos]# bin/startup.sh -m standalone

登录控制台

http://192.168.1.137:8848/nacos

服务注册

IDEA 2022 版本

provider 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">
    <parent>
        <artifactId>springclound</artifactId>
        <groupId>com.hztech</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>provider-payment8002</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>


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

        <!-- nacos注册中心 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</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>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!--mysql-connector-java-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</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>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>


    </dependencies>


</project>

yaml:

server:
  port: 8002
spring: application: name: cloud-payment-service # 项目名,也是注册的名字 cloud: nacos: discovery: server-addr: 192.168.1.137:8848


main()
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class PaymentMain8002 {

    public static void main(String[] args) {

        SpringApplication.run( PaymentMain8002.class, args);

    }

}

 

 

Controller中增加降级 注解

注意 :降级函数的返回值类型和参数类型要保持一致。

    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_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 = "60"),// 失败率达到多少后跳闸
    }) // 在10s内10次请求有60%失败 // 请求次数要先满足,再看百分比

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable( "id")  Long id)
    {

        Payment payment = paymentService.getPaymentById(id);
        logger.info("***********查询结果:"+payment+"\t"+"oo哈哈 ——##"+port);

        if(id<0){
            System.out.println("*****id 不为负数");
            throw new RuntimeException("*****id 不为负数");
        }
        /**
         * huTool工具包的方法
         * 在自定义的cloud-api-commons里引入了
         */
        String serialNumber = IdUtil.simpleUUID();
        String tip = Thread.currentThread().getName()+"\t"+"调用成功,流水号: "+serialNumber;

        if (payment!=null){
            return new CommonResult(200,"查询成功"+port +tip,payment);
        }else {
            return new CommonResult(444,"查询失败"+port,null);
        }

    }

    public CommonResult<Payment> paymentCircuitBreaker_fallback(@PathVariable("id") Long id){
        return new CommonResult(444,port+"id不能为负数,请稍候再试,/(T o T)/~~ id: "+id,null);
        //return "id不能为负数,请稍候再试,/(T o T)/~~ id: "+id;
    }

消费端order 启用降级 ,回调类 实现 Feign调用接口

 

 

pox.xml

同上面的 provider 8002

Main 启用 @EnableFeignClients 和@EnableHystrix

 
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrix
public class OrderMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderMain80.class,args);
    }
}

yml配置

server:
  port: 88
spring:
  cloud:
   
    nacos:
      discovery:
        server-addr: 192.168.1.137:8848
    inetutils:
      ignored-interfaces: 'VMware Virtual Ethernet Adapter for VMnet1,VMware Virtual Ethernet Adapter for VMnet8'
  application:
    name: payment-order

 

 

启动服务:

 

 

测试:

 

 两台provider服务器 轮询

 

 

多次错误请求触发 fallback 后,正常请求,测试服务降级

 

 

 

 

稍后再试:恢复正常

 

 

 

@HystrixCommand所有配置

@HystrixCommand(fallbackMethod = "str_fallbackMethod",
        groupKey = "strGroupCommand",
        commandKey = "strCommand",
        threadPoolKey = "strThreadPool",
        commandProperties = {
                // 设置隔离策略,THREAD 表示线程池 SEMAPHORE:信号池隔离
                @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                // 当隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
                @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
                // 配置命令执行的超时时间
                @HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
                // 是否启用超时时间
                @HystrixProperty(name = "execution.timeout.enabled", value = "true"),
                // 执行超时的时候是否中断
                @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
                // 执行被取消的时候是否中断
                @HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
                // 允许回调方法执行的最大并发数
                @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
                // 服务降级是否启用,是否执行回调函数
                @HystrixProperty(name = "fallback.enabled", value = "true"),
                // 是否启用断路器
                @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
                // 该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为 20 的时候,
                // 如果滚动时间窗(默认10秒)内仅收到了19个请求, 即使这19个请求都失败了,断路器也不会打开。
                @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
                // 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过
                // circuitBreaker.requestVolumeThreshold 的情况下,如果错误请求数的百分比超过50,
                // 就把断路器设置为 "打开" 状态,否则就设置为 "关闭" 状态。
                @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
                // 该属性用来设置当断路器打开之后的休眠时间窗。 休眠时间窗结束之后,
                // 会将断路器置为 "半开" 状态,尝试熔断的请求命令,如果依然失败就将断路器继续设置为 "打开" 状态,
                // 如果成功就设置为 "关闭" 状态。
                @HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5000"),
                // 断路器强制打开
                @HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
                // 断路器强制关闭
                @HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
                // 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
                @HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
                // 该属性用来设置滚动时间窗统计指标信息时划分"桶"的数量,断路器在收集指标信息的时候会根据
                // 设置的时间窗长度拆分成多个 "桶" 来累计各度量值,每个"桶"记录了一段时间内的采集指标。
                // 比如 10 秒内拆分成 10 个"桶"收集这样,所以 timeinMilliseconds 必须能被 numBuckets 整除。否则会抛异常
                @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
                // 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为 false, 那么所有的概要统计都将返回 -1。
                @HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"),
                // 该属性用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
                @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
                // 该属性用来设置百分位统计滚动窗口中使用 “ 桶 ”的数量。
                @HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
                // 该属性用来设置在执行过程中每个 “桶” 中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,
                // 就从最初的位置开始重写。例如,将该值设置为100, 滚动窗口为10秒,若在10秒内一个 “桶 ”中发生了500次执行,
                // 那么该 “桶” 中只保留 最后的100次执行的统计。另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
                @HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
                // 该属性用来设置采集影响断路器状态的健康快照(请求的成功、 错误百分比)的间隔等待时间。
                @HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
                // 是否开启请求缓存
                @HystrixProperty(name = "requestCache.enabled", value = "true"),
                // HystrixCommand的执行和事件是否打印日志到 HystrixRequestLog 中
                @HystrixProperty(name = "requestLog.enabled", value = "true"),
        },
        threadPoolProperties = {
                // 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
                @HystrixProperty(name = "coreSize", value = "10"),
                // 该参数用来设置线程池的最大队列大小。当设置为 -1 时,线程池将使用 SynchronousQueue 实现的队列,
                // 否则将使用 LinkedBlockingQueue 实现的队列。
                @HystrixProperty(name = "maxQueueSize", value = "-1"),
                // 该参数用来为队列设置拒绝阈值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
                // 该参数主要是对 LinkedBlockingQueue 队列的补充,因为 LinkedBlockingQueue
                // 队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
                @HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
        }
)

 

标签:OpenFeign,Hystrix,SpringCloud,boot,value,HystrixProperty,spring,id,name
From: https://www.cnblogs.com/hztech/p/17126638.html

相关文章

  • CICD流水线 Jenkins搭建 及构建后端SpringCloud项目
    一、CICD在CI/CD和DevOps领域中,持续交付和持续部署是一个老生常谈的话题。持续集成这个术语最早是在1994年由GradyBooch提出。微服务提出者MartinFlower在2014年发表的......
  • OpenFeign-远程调用工具
    介绍声明式的http客户端,底层还是HttpClient,可以解决RestTemplate硬编码进行远程服务调用的缺点官网:https://github.com/OpenFeign/feign入门以A微服务对B微服务远程调......
  • OpenFeign 4.0.1+SpringCloud3.0.x+Consul集群
    介绍OpenFeignopenFeign是工作在客户端可与其他注册发现管理服务器整合(eureka,zookeeper,consul,nacos等)功能上替代了restTemplate,本身集成Ribbon有负载均衡功能,在形式......
  • springcloud之配置中心config
    1、指定读取的配置路径配置在application.yml文件里面server:port:${SERVER_PORT:10102}spring:application:name:configprofiles:active:${PR......
  • springcloud项目搭建遇到问题记录
    1.&yml文件配置Facets(表述了在Module中使用的各种各样的框架、技术和语言。这些Facets让IntellijIDEA知道怎么对待module内容,并保证与相应的框架和语言保持一致。)添加spri......
  • springcloud微服务搭建demo
    软件版本IDEA2022.3.1<兼容maven3.8.1及之前的所用版本>JDK1.8_64Maven3.8.2本demo只使用了服务发现与注册、Feign调用及负载均衡。不涉及熔断与......
  • springcloud sidecar 实现C语言调用语言模块
    以前对springcloud的印象停留在大项目功能模块的独立、负载均衡、熔断等功能。这次项目接触了另一个用法,多语言异构。以前Java调C都是用的JNA或者JNI,这次C调Java用了spring......
  • 微服务学习计划——SpringCloud
    微服务学习计划——SpringCloud在学习并掌握了众多基础框架之后,我们的项目繁杂且难以掌握,那么我们就需要开启一门新的课程,也就是我们常说的微服务架构随着互联网行业的发......
  • SpringCloud 集成 Consul+restTemplate 集群实战
      服务提供者应用两个模块(prot:8021,8021)pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmln......
  • Docker 服务编排 快速部署 SpringCloud 项目 (一)
    一、docker-compose.ymlversion:"3.3"networks:zeal:volumes:data:services:gateway:restart:alwaysbuild:context:./gateway......