openfeign集成sentinel实现服务降级

news2024/10/5 13:48:53

openfeign集成sentinel实现服务降级

  • 使用openfeign调用服务(不含sentinel)
    • 代码
    • 测试
  • openfeign集成sentinel实现服务降级
    • 引入sentinel相关环境
    • 编写@FeignClient注解接口的实现类
    • 在服务提供者中,认为添加异常代码,以供测试 / 或者不启动服务提供者,服务消费者找不到服务提供者,也会报错,同样能够达到测试效果!
    • 测试,启动服务提供者及服务消费者
  • 未完待续:使用工厂模式来实现Fallback

使用openfeign调用服务(不含sentinel)

代码

application.properties

server.port=8083
spring.application.name=nacos-consumer02
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.discovery.enabled=true

spring.cloud.nacos.username=nacos
spring.cloud.nacos.password=nacos

#feign.sentinel.enabled=true

#开启热部署
#spring.devtools.restart.enabled=true

主启动类

package com.xl.projects;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumer02Application {
	public static void main(String[] args) {
		SpringApplication.run(NacosConsumer02Application.class, args);
	}
}

Controller

package com.xl.projects.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xl.projects.feign.Consumer02Feign;

@RestController
public class Consumer02Controller {
	
	@Resource
	private Consumer02Feign consumer02Feign;
	
	@GetMapping("/another/consumer")
	public String testInvoke() {
		return consumer02Feign.invokeProvider("oooh!~~~,this is another consumer,named consumer02");
	}
	
}

@FeignClient注解的接口

package com.xl.projects.feign;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "nacos-provider",fallback = FeignFallbackImpl.class)
public interface Consumer02Feign {

	/**
	 * 	注意!!!,这里需要显示的指定@RquestParam,否者调用的时候会报错!
	 * 
	 * @param param
	 * @return
	 */
	@GetMapping("/provider/test")
	String invokeProvider(@RequestParam String param);
}

以上代码为服务调用者(消费者)代码,以下为服务提供者的Controller代码,其他部分略:

package com.xl.projects.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * For Test!!!
 * @author xl
 *
 */
@RestController
public class TestProviderController {
	
	
	@Value("${spring.application.name}")
    private String appName;
	
	/**
	 * For Test!
	 * @param param
	 * @return
	 */
	@GetMapping("/provider/test")
	public String test(String param) {
//		throw new RuntimeException("服务端测试异常!");
		return new Date().getSeconds()+
				", this is provider return msg: current param="+param;
	}
	
	@GetMapping("/test")
	public String testParam() {
		return appName;
	}
}

pom.xml 中需添加spring cloud open feign的依赖:

<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">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.xl.projects</groupId>
		<artifactId>xl-springcloud-parent-pom</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>xl-nacos-cunsumer02</artifactId>


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

		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
		
<!-- 		<dependency> -->
<!--             <groupId>com.alibaba.cloud</groupId> -->
<!--             <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> -->
<!--         </dependency> -->
        
<!--         <dependency> -->
<!-- 			<groupId>org.springframework.boot</groupId> -->
<!-- 			<artifactId>spring-boot-devtools</artifactId> -->
<!-- 			<scope>test</scope> -->
<!-- 		</dependency> -->

	</dependencies>

</project>

测试

启动Nacos, 启动服务提供者项目以及服务消费者项目。浏览器访问:http://localhost:8083/another/consumer :
在这里插入图片描述
上图说明使用openfeign调用成功。

在上面@FeignClient注解的接口代码中,@FeignClient注解有个属性fallback!这个fallback是干什么用的呢?见官网:
https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/#spring-cloud-feign-circuitbreaker

在这里插入图片描述

Spring Cloud CircuitBreaker supports the notion of a fallback: a default code path that is executed when the circuit is open
 or there is an error.

大意翻译 : 当遇到一个错误或者熔断器处于开放状态,那么程序就会执行fallback属性配置的类!

To enable fallbacks for a given @FeignClient set the fallback attribute to the class name that implements the fallback. 
You also need to declare your implementation as a Spring bean.

大意翻译 : fallback配置的类需要实现@FeignClient配置的接口,并且还的是一个Spring bean (类上需要加上@Component注解!)

根据以上翻译内容,“当程序遇到错误时,就会执行fallback配置的类” ,说明fallback可以充当服务降级的作用,那如何通过fallback来实现服务降级呢?

openfeign集成sentinel实现服务降级

可通过openfeign的注解@FeignClient的属性fallback结合sentinel实现服务降级!

引入sentinel相关环境

引入依赖

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

application.properties中引入配置(启用):feign.sentinel.enabled=true

server.port=8083
spring.application.name=nacos-consumer02
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.discovery.enabled=true

spring.cloud.nacos.username=nacos
spring.cloud.nacos.password=nacos

feign.sentinel.enabled=true

#开启热部署
#spring.devtools.restart.enabled=true

编写@FeignClient注解接口的实现类

package com.xl.projects.feign;

import org.springframework.stereotype.Component;

@Component
public class FeignFallbackImpl implements Consumer02Feign {

	@Override
	public String invokeProvider(String param) {
		return ">>>>>>>>>>>>fallback results>>>>>>>>>>>>";
	}

}

在这里插入图片描述

在服务提供者中,认为添加异常代码,以供测试 / 或者不启动服务提供者,服务消费者找不到服务提供者,也会报错,同样能够达到测试效果!

在这里插入图片描述

测试,启动服务提供者及服务消费者

启动服务消费者时,控制台报错,启动失败!

Caused by: java.lang.IllegalAccessError: class org.springframework.cloud.openfeign.HystrixTargeter$$EnhancerBySpringCGLIB$$29430b6f cannot access its superclass org.springframework.cloud.openfeign.HystrixTargeter
	at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_201]
	at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_201]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_201]
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_201]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_201]
	at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_201]
	at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:535) ~[spring-core-5.2.15.RELEASE.jar:5.2.15.RELEASE]
	... 78 common frames omitted

解决:
删除/取消项目热部署,但,有个问题是热部署依赖是在父项目的pom中的,直接屏蔽掉,其他子项目都无法使用热部署的功能了。所以,需要将热部署的依赖拷贝到本服务消费的pom中,同时将<scope>改为test。因为这样会覆盖父pom中的依赖,同时scope为test也不会影响正常的编译阶段和运行阶段。

修改后 :

<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">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.xl.projects</groupId>
		<artifactId>xl-springcloud-parent-pom</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>xl-nacos-cunsumer02</artifactId>


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

		<dependency>
			<groupId>com.alibaba.cloud</groupId>
			<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
		
		<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>test</scope>
		</dependency>

	</dependencies>

</project>

再次启动,成功!访问地址 :http://localhost:8083/another/consumer
在这里插入图片描述
验证成功!

未完待续:使用工厂模式来实现Fallback

FallbackFactory工厂

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/196215.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBean的生命周期

下文要讲的均是spring的默认作用域singleton的bean的生命周期&#xff0c;对spring作用域不了解的可以 https://blog.csdn.net/hlzdbk/article/details/128811271?spm1001.2014.3001.5502 什么是SpringBean的生命周期 springBean的生命周期&#xff0c;指的是spring里一个be…

Python爬虫以及数据可视化分析之某站热搜排行榜信息爬取分析

目录前言一&#xff0c;确定目标二&#xff0c;发送请求三, 解析数据四, 保存数据pyecharts进行可视化“某站”数据排名前10视频类型“某站”标题标签可视化“某站”喜欢视频分类概况总结前言 本项目将会对“某站”热搜排行的数据进行网页信息爬取以及数据可视化分析 本教程仅…

数据结构:栈的学习

作者&#xff1a;爱塔居 专栏&#xff1a;数据结构 作者简介&#xff1a;大三学生&#xff0c;希望跟大家一起进步 目录 一、栈 1.1 概念 1.2 栈的使用 1.3 示例 二、栈的应用场景 2.1 改变元素的序列 2.2 逆波兰表达式求值 2.3 括号匹配 2.4 栈的压入、弹出序列 一、栈…

upstream sent duplicate header line: “Transfer-Encoding: chunked“

实际情景&#xff1a; 公司项目有一个下载文件的功能&#xff0c;没有经过Nginx代理之前&#xff0c;好好的&#xff0c;正常下载&#xff1b; 加入了Nginx代理之后&#xff0c;过Nginx访问就会有 err_empty_response 这个错误&#xff1b; 搞了半天&#xff0c;nginx.conf加入…

第一章 linux概述

第一章 Linux概述 1、为什么要使用Linux Linux内核最初只是由芬兰人林纳斯托瓦兹&#xff08;Linus Torvalds&#xff09;在赫尔辛基大学上学时出于个人爱好而编写的。 Linux是一套免费使用和自由传播的类Unix操作系统&#xff0c;是一个基于POSIX和UNIX的多用户、多任务、支…

【蓝桥杯_学习_51单片机】矩阵键盘 状态机法

矩阵键盘 一.基础知识 在键盘中按键数量较多时&#xff0c;为了减少I/O口的占用&#xff0c;通常将按键排列成矩阵形式采用逐行或逐列的“扫描”&#xff0c;就可以读出任何位置按键的状态 矩阵键盘和独立按键一样&#xff0c;也需要进行消抖处理&#xff01; 于此补充一下抖…

c++之基础入门一

一、c的初始化typedef struct student {int age;char name[10];int num; }student;int main() {//在c中可以利用花括号进行初始化struct student student1{12,"zs",123456 };int a 10, b 20;int b{ 20 }, a{ 10 };double c{ 20 };int* p{ nullptr };int arr[10]{ 1…

Day877.数据空洞 -MySQL实战

数据空洞 Hi&#xff0c;我是阿昌&#xff0c;今天学习记录的是关于数据空洞的内容。 数据库占用空间太大&#xff0c;把一个最大的表删掉了一半的数据&#xff0c;怎么表文件的大小还是没变&#xff1f; 一个 InnoDB 表包含两部分&#xff0c;即&#xff1a; 表结构定义数…

我通过 tensorflow 预测了博客的粉丝数

前言&#xff1a;由于最近接触了 tensorflow.js&#xff0c;出于试一下的心态&#xff0c;想通过线性回归预测一下博客的粉丝走向和数量&#xff0c;结果翻车了。虽然场景用错地方&#xff0c;但是整个实战方法用在身高体重等方面的预测还是有可行性&#xff0c;所以就记录下来…

亚马逊云科技助力游戏上云学习心得-增长篇

云服务已经是大势所趋了&#xff0c;通过购置传统服务器来进行应用开发&#xff0c;无法与现代化敏捷的开发方法相结合&#xff0c;对于系统运维的难度也大大增加&#xff0c;而云服务的弹性伸缩、动态计费可以很好地帮助中小企业实现快速应用开发&#xff0c;使得产品的价值最…

LeetCode题目笔记——1337. 矩阵中战斗力最弱的 K 行

文章目录题目描述题目难度——简单方法一&#xff1a;暴力&#xff0c;统计代码/Python方法二&#xff1a;优化代码总结彩蛋题目描述 给你一个大小为 m * n 的矩阵 mat&#xff0c;矩阵由若干军人和平民组成&#xff0c;分别用 1 和 0 表示。 请你返回矩阵中战斗力最弱的 k 行…

Dubbo服务方消费方通信案例

文章目录Maven_服务方Maven_服务消费方测试通信使用注册中心自动找服务设置超时时间重试次数单独设置某个方法不可重试处理多版本的问题本地存根策略负载均衡策略Dubbo高可用服务降级服务降级实现方式Maven_服务方 pom文件&#xff0c;注意依赖的版本。 <properties><…

《无线电发射设备管理规定》解读

2022年12月22日&#xff0c;工业和信息化部公布了《无线电发射设备管理规定》&#xff08;工业和信息化部令第57号&#xff0c;以下简称《规定》&#xff09;。为了更好地理解和执行《规定》&#xff0c;工业和信息化部产业政策与法规司负责同志对《规定》进行了解读。 问题一 …

7.卷积神经网络

7.卷积神经网络 目录 从全连接层到卷积图像卷积 互相关运算&#xff08;手撕卷积&#xff09;卷积层图像中目标的边缘检测学习卷积核 填充和步幅 填充Padding步幅stride 多输入多输出通道 多输入通道多输出通道11 卷积层总结 池化层 最大池化层和平均池化层填充和步幅多个通道…

Matlab 与 Excel 文件的交互

事实上&#xff0c;excel可以解决绝大多数的建模问题&#xff0c;只不过&#xff0c;更加复杂。。。而且难以操作。。。其实可以看看excel的 功能还是很多的不过嘛 术业有专攻的 有专攻的多主体 NetLogo仿真 Comsol 。。。Excel 文件写入向量与张量的excel写入xlswrite(<pat…

JTAG 基础和svf specification介绍

参考&#xff1a; https://www.youtube.com/watch?vUuDf3q5aBjM https://zh.m.wikipedia.org/zh-cn/JTAG浅谈dft之boundary scan JTAG: Joint Test Action Group是开发IEEE 1149.1的工作组&#xff0c;1149.1定义了一个测试开发版上芯片的标准。现在变成了芯片的一个最常见…

yolov5增加iou loss,无痛涨点trick

yolo无痛涨点trick&#xff0c;简单实用 先贴一张最近一篇论文的结果 后来的几种iou的消融实验结果在一定程度上要优于CIoU&#xff0c;最新的WIoU暂时还没复现。 本文将在yolov5的基础上增加SIoU&#xff0c;EIoU&#xff0c;Focal-XIoU&#xff08;X为C,D,G,E,S等&#xff09…

使用Kindling 观测 Kubernetes 应用网络连接状态

kindling介绍&#xff1a; Kindling 解决的是&#xff0c;在不入侵应用的前提下&#xff0c;如何观测网络的问题&#xff0c;其功能主要是通过暴露内核事件来实现观测。如果主机内核版本高于 4.14&#xff0c;可以使用 eBPF 模块&#xff1b;如果主机内核是低版本&#xff0c;…

多级缓存实现

多级缓存实现1.什么是多级缓存2.JVM进程缓存2.1.导入案例2.2.初识Caffeine2.3.实现JVM进程缓存2.3.1.需求2.3.2.实现3.Lua语法入门3.1.初识Lua3.1.HelloWorld3.2.变量和循环3.2.1.Lua的数据类型3.2.2.声明变量3.2.3.循环3.3.条件控制、函数3.3.1.函数3.3.2.条件控制3.3.3.案例4…

俯卧撑计数 opencv-python + mediapipe

分享一个国外的趣味项目&#xff0c;可以计数&#xff0c;也可以完善进行动作是打分&#xff0c;确定标准程度 原文链接&#xff1a;https://aryanvij02.medium.com/push-ups-with-python-mediapipe-open-a544bd9b4351 程序原理介绍 在新加坡军队中&#xff0c;有一种测试叫做…