微服务之服务保护

Sentinel引入Java项目中

一:安装Sentinel

官网地址:https://github.com/alibaba/Sentinel/releases

二:安装好后在sentinel-dashboard.jar所在目录运行终端

三:运行命令,端口自己指定

复制代码
java -Dserver.port=8090 -Dcsp.sentinel.dashboard.server=localhost:8090 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

四:然后访问,localhost:8090 账号密码刚开始默认是sentinel

五:项目中引入依赖

复制代码
<!--sentinel-->
<dependency>
    <groupId>com.alibaba.cloud</groupId> 
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

六:配置application.yaml

复制代码
spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8090
      http-method-specify: true # 开启请求方式前缀

fallback

一般簇点链路都是springmvc的接口,如果要基于openfeign的远程调用也加入簇点链路,就需要一个配置

复制代码
feign:
  sentinel:
    enabled: true

FeignClient的Fallback有两种配置方式:

  • 方式一:FallbackClass,无法对远程调用的异常做处理
  • 方式二:FallbackFactory,可以对远程调用的异常做处理,通常都会选择这种

步骤一:自定义类,实现FallbackFactory,编写对某个FeignClient的fallback逻辑

java 复制代码
@Slf4j
public class ItemClientFallbackFactory implements FallbackFactory<ItemClient> {
    @Override
    public ItemClient create(Throwable cause) {
        // 创建ItemClient接口实现类,实现其中的方法,编写失败降级的处理逻辑
        return new ItemClient() {
            @Override
            public List<ItemDTO> getItemByIds(Collection<Long> ids) {
                log.error("查询商品信息失败,cause: {}", cause.getMessage());
                return CollUtils.emptyList();
            }

            @Override
            public void deductStock(List<OrderDetailDTO> items) {
                throw new RuntimeException("扣减商品库存失败");
            }
        };
    }
}

步骤二:在配置类中把这个类注册为一个bean

java 复制代码
@Bean
public ItemClientFallbackFactory createItemClientFallbackFactory(){
   return new ItemClientFallbackFactory();
}

步骤三:在userClient接口中使用ItemClientFallbackFactory

java 复制代码
@FeignClient(value = "item-service",fallbackFactory = ItemClientFallbackFactory.class)
public interface ItemClient {
    @GetMapping("/items")
    List<ItemDTO> getItemByIds(@RequestParam("ids") Collection<Long> ids);
    @PutMapping("/items/stock/deduct")
    void deductStock(@RequestBody List<OrderDetailDTO> items);
}

服务熔断

熔断降级是解决雪崩问题的重要手段。思路是由断路器统计服务调用的异常比例,慢请求比例,如果超出阈值则会熔断该服务。即拦截访问该服务的一切请求;当服务恢复时,断路器会放行访问该服务的请求。

相关推荐
廋到被风吹走6 天前
稳定性保障:限流降级深度解析 —— Sentinel滑动窗口算法与令牌桶实现
运维·算法·sentinel
笨蛋不要掉眼泪10 天前
Sentinel 热点参数限流实战:精准控制秒杀接口的流量洪峰
java·前端·分布式·spring·sentinel
笨蛋不要掉眼泪11 天前
Sentinel 流控规则详解:三种模式与三种效果实战指南
java·jvm·数据库·后端·sentinel
Jinkxs12 天前
Sentinel - 在 Dubbo 微服务中使用:Alibaba 生态无缝集成
微服务·sentinel·dubbo
笨蛋不要掉眼泪12 天前
Spring Cloud Alibaba Sentinel 从入门到实战:微服务稳定性的守护者
分布式·微服务·云原生·架构·sentinel
tod11312 天前
Redis Sentinel 高可用架构:从原理到 Docker 部署全解析
数据库·redis·docker·架构·sentinel
递归尽头是星辰14 天前
Sentinel + Spring Cloud Gateway 联动限流实战
系统架构·sentinel·限流·微服务治理·限流架构设计
万象.14 天前
redis哨兵sentinel的部署及作用
redis·sentinel
七夜zippoe15 天前
分布式系统弹性设计实战:Hystrix与Sentinel熔断降级深度解析
java·hystrix·sentinel·aws·分布式系统
程序员敲代码吗16 天前
微服务熔断降级配置详解与实践:使用Sentinel和Nacos
java·微服务·sentinel