OpenFeign集成Sentinel

一:引入依赖

<!--sentinel依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--引入OpenFeign依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

二:配置文件application开启OpenFeignSentinel熔断

server:
    port: 10002 #order服务端口号

spring:
    application:
        name: order-server #应用名称
    cloud:
        nacos:
            discovery:
                server-addr: localhost:8848 #指定nacos注册中心地址
feign:
    sentinel:
        enabled: true #开启熔断功能

 三:熔断工厂

package cn.ybl.feign;

import cn.ybl.domain.User;
import feign.hystrix.FallbackFactory;

/**
  * UserFeign的熔断工厂类
  */
public class UserFeignClientFallbackFactory implements FallbackFactory<UserFeign> {

    /**
	  * 熔断托底方法
      * @param throwable
	  */
    @Override
    public UserFeign create(Throwable throwable) {
        return new UserFeign() {
            @Override
            public User getUser(Long id) {
                return new User(-1L, "触发熔断", "服务不可用,请稍后重试!");
            }
        };
    }
}

四:Feign接口通过feign客户端注解指向熔断工厂

package cn.ybl.feign;

import cn.ybl.domain.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(value = "user-server",fallbackFactory = UserFeignClientFallbackFactory.class)
@RequestMapping("/user")
public interface UserFeign {

    @GetMapping("/getById/{id}")
    User getUser(@PathVariable("id") Long id);
}

如此便完成了OpenFeign整合Sentinel,当调用此feign接口出现异常时则触发熔断,返回托底数据

posted @ 2022-08-23 19:13  yyybl  阅读(147)  评论(0)    收藏  举报