依赖:

<!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--sentinel-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

yaml:

feign:
  sentinel:
    enabled: true      # 添加sentinel 对 feign 的支持

跟@FeignClient里面加上Hytrix熔断一样,直接使用fallback就可以了
案例:

package com.bear.client;

import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.bear.excep.ExceptionExcep;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;

/**  feign调用nacos-provide服务,调用里面的方法
 * @author LiuShanshan
 * @version V1.0
 * @Description
 */
@FeignClient(value = "nacos-provide", fallback = ExceptionExcep.class)   // 使用sentinel替换hystrix(这里是直接在括号里面写fallback)
public interface ProvideService {

    @RequestMapping("/provideGet")
    public String provideGet();
}

失败的回调类里面的方法:

package com.bear.excep;

import com.bear.client.ProvideService;
import org.springframework.stereotype.Component;

/**
 * @author LiuShanshan
 * @version V1.0
 * @Description
 */
@Component
public class ExceptionExcep implements ProvideService{
    @Override
    public String provideGet() {
        System.out.println("调用服务失败,此地方进行处理");
        return null;
    }

}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐