# 概述

服务降级是一种增强用户体验的方式。

用户的请求由于各种原因被拒后,系统返回一个事先设定好的、用户可以接受的,但又令用户并不满意的结果。这种请求处理方式称为服务降级。

# 方法级

  1. 添加依赖
  2. 定义接口方法
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/sen")
@RestController
public class ProviderController {

    @GetMapping
    //申明降级方法
    @SentinelResource(fallback = "serviceDownFallBack")
    public String list() {
        int i = 5 / 0;
        return "sentinel list ";
    }

    /**
     * 定义服务降级方法
     */
    public String serviceDownFallBack(Throwable e) {
        return "list -- 服务降级\n" + e.getMessage();
    }
}

# 类级别

  1. 定义类申明返回的降级方法(static的)
public class GlobalControllerFallBackMessage {

    public static String handlerFallbackMessage() {
        return "类级别 服务降级";
    }
}
  1. 需要降级方法上使用
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/sen")
@RestController
public class ProviderController {

    @GetMapping
    @SentinelResource(fallback = "handlerFallbackMessage", fallbackClass = GlobalControllerFallBackMessage.class)
    public String list() {
        int i = 5 / 0;
        return "sentinel list ";
    }

}

# Feign 式服务降级

  1. 申明远程 Feign 接口
@FeignClient(value = "provider-8081", path = "/depart", fallback = DepartFeignFallbackServiceImpl.class)
public interface DepartFeignService {

    @GetMapping("{id}")
    Depart getById(@PathVariable("id") Integer id);

}
  1. 降级类实现声明的 Feign 接口
@Component
public class DepartFeignFallbackServiceImpl implements DepartFeignService {

    @Override
    public Depart getById(Integer id) {
        return new Depart(5,"Feign 服务降级");
    }
}
  1. controller 提供接口
@RequestMapping("/sen")
@RestController
public class ProviderController {
    @Autowired
    private DepartFeignService departFeignService;

    @GetMapping("open")
    public Depart select() {
        return departFeignService.getById(1);
    }
}

# Feign 式服务降级无法降级问题

# 降级类实现声明的 Feign 接口,增加 @RequestMapping("/depart") 注解,地址和 Feign 需要一致

# 在 spring cloud alibaba 2022.0.0.0 版本 需要增加配置

spring:
  cloud:
    openfeign:
      lazy-attributes-resolution: true