openfeign作为微服务各个模块之间调用的组件,如果服务提供方出现异常,会将错误返回给服务消费方,消费方可以通过sentinel的服务降级方法,对如果调用异常的情况进行处理
以下介绍下具体做法:
一、服务消费方必须整合openfeign,方法可以参考:https://www.cnblogs.com/qwg-/p/18007449
pom.xml中必须添加以下依赖:
<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>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
二、在application.yml文件中添加
server:
port: 8090
spring: application: name: order-sentinel-openfeign cloud: sentinel: transport: dashboard: 127.0.0.1:8080 nacos: discovery: server-addr: 127.0.0.1:8848 username: nacos password: nacos namespace: public feign: sentinel: enabled: true #尤其是这个
三、代码
StockFeignService为feign接口
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "stock-service",path = "/stock",fallback = StockFeignFabackImpl.class) //name为服务名称,path为接口路径 public interface StockFeignService { @GetMapping("/reduce2") String reduce2(); }
StockFeignFabackImpl为feign接口的实现类,该方法就是降级后执行的方法
@Component // 注意需要添加到spring容器中 public class StockFeignFabackImpl implements StockFeignService { @Override public String reduce2() { return "被降级"; } }
被调用方(服务提供者)
@RestController @RequestMapping("/stock") public class StockController { @GetMapping("/reduce2") public String reduce2(){ int a = 1/0; //故意造异常 System.out.println("扣减库存"); return "扣减库存 " + port; }
controller测试demo
@RestController @RequestMapping("/order") public class OrderController { @Resource StockFeignService stockFeignService; @GetMapping("/openfeign") public String openfeign(){ String msg = stockFeignService.reduce2(); return "hello " + msg; }
测试请求
以上内容纯学习使用!
标签:openfeign,sentient,springcloud,reduce2,spring,sentinel,public,cloud From: https://www.cnblogs.com/qwg-/p/18429277