sentinel源码分析-01客户端启动和注册

springcloud alibaba——@sentinelResource注解的使用(全局) 传统@sentinelResource注解使用的缺陷: 1、系统默认的,没有体现我们自己的业务要求。 2、依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。 3、每个业务方法都添加一个兜底的,那代码膨胀加剧。 4、全局统一的处理方法没有体现。 解决办法:定义一个兜底方法的工具类,全局都可以使用。 1、工具类 package com.springcloud.myHandler; import com.alibaba.csp.sentinel.slots.block.BlockExcepti 阅读详情

1.客户端启动和注册

在引入sentinel组建后,启动时会通过spi机制加载spring.factories文件中的自动配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.alibaba.cloud.sentinel.SentinelWebAutoConfiguration,\
com.alibaba.cloud.sentinel.SentinelWebFluxAutoConfiguration,\
com.alibaba.cloud.sentinel.endpoint.SentinelEndpointAutoConfiguration,\
com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration,\
com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration

org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\
com.alibaba.cloud.sentinel.custom.SentinelCircuitBreakerConfiguration

SentinelWebAutoConfiguration类中声明了一个FilterRegistrationBean,在这个方法中创建了一个核心类CommonFilter,拦截所有请求

@Bean
@ConditionalOnProperty(
    name = {"spring.cloud.sentinel.filter.enabled"},
    matchIfMissing = true
)
public FilterRegistrationBean sentinelFilter() {
    FilterRegistrationBean<Filter> registration = new FilterRegistrationBean();
    com.alibaba.cloud.sentinel.SentinelProperties.Filter filterConfig = this.properties.getFilter();
    if(filterConfig.getUrlPatterns() == null || filterConfig.getUrlPatterns().isEmpty()) {
        List<String> defaultPatterns = new ArrayList();
        //拦截所有请求
        defaultPatterns.add("/*");
        filterConfig.setUrlPatterns(defaultPatterns);
    }

    registration.addUrlPatterns((String[])filterConfig.getUrlPatterns().toArray(new String[0]));
    Filter filter = new CommonFilter();
    registration.setFilter(filter);
    registration.setOrder(filterConfig.getOrder());
    registration.addInitParameter("HTTP_METHOD_SPECIFY", String.valueOf(this.properties.getHttpMethodSpecify()));
    log.info("[Sentinel Starter] register Sentinel CommonFilter with urlPatterns: {}.", filterConfig.getUrlPatterns());
    return registration;
}

查看CommonFilter.doFilter方法

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //拦截过滤
    HttpServletRequest sRequest = (HttpServletRequest) request;
    Entry urlEntry = null;
    Entry httpMethodUrlEntry = null;

    try {
        //返回资源路径
        String target = FilterUtil.filterTarget(sRequest);
        // Clean and unify the URL.
        // For REST APIs, you have to clean the URL (e.g. `/foo/1` and `/foo/2` -> `/foo/:id`), or
        // the amount of context and resources will exceed the threshold.
        UrlCleaner urlCleaner = WebCallbackManager.getUrlCleaner();
        if (urlCleaner != null) {
            target = urlCleaner.clean(target);
        }

        // If you intend to exclude some URLs, you can convert the URLs to the empty string ""
        // in the UrlCleaner implementation.
        if (!StringUtil.isEmpty(target)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(sRequest);
            //初始化sentinel上下文
            ContextUtil.enter(WebServletConfig.WEB_SERVLET_CONTEXT_NAME, origin);
            //核心逻辑-资源检查
            urlEntry = SphU.entry(target, EntryType.IN);
            // Add method specification if necessary
            if (httpMethodSpecify) {
                httpMethodUrlEntry = SphU.entry(sRequest.getMethod().toUpperCase() + COLON + target,
                        EntryType.IN);
            }
        }
        //继续往下执行其他过滤器
        chain.doFilter(request, response);
    } catch (BlockException e) {
        HttpServletResponse sResponse = (HttpServletResponse) response;
        // Return the block page, or redirect to another URL.
        WebCallbackManager.getUrlBlockHandler().blocked(sRequest, sResponse, e);
    } catch (IOException | ServletException | RuntimeException e2) {
        Tracer.traceEntry(e2, urlEntry);
        Tracer.traceEntry(e2, httpMethodUrlEntry);
        throw e2;
    } finally {
        if (httpMethodUrlEntry != null) {
            httpMethodUrlEntry.exit();
        }
        if (urlEntry != null) {
            urlEntry.exit();
        }
        ContextUtil.exit();
    }
}

SphU.entry(target, EntryType.IN)是资源检查的核心逻辑

public static Entry entry(String name, EntryType type) throws BlockException {
    //Env有静态代码块
        return Env.sph.entry(name, type, 1, OBJECTS0);
    }

Env类

public class Env {

    public static final Sph sph = new CtSph();

    static {
        // If init fails, the process will exit.
        //初始化
        InitExecutor.doInit();
    }

}

执行初始化doInit方法

public static void doInit() {
    //保证只会初始化一次
    if (!initialized.compareAndSet(false, true)) {
        return;
    }
    try {
        //SPI
        //加载"META-INF/services/"目录下所配置的所有实现了InitFunc接口的类
        ServiceLoader<InitFunc> loader = ServiceLoader.load(InitFunc.class);
        List<OrderWrapper> initList = new ArrayList<OrderWrapper>();
        for (InitFunc initFunc : loader) {
            RecordLog.info("[InitExecutor] Found init func: " + initFunc.getClass().getCanonicalName());
            //根据InitOrder注解对初始化实现类进行排序,值越小优先级越高
            insertSorted(initList, initFunc);
        }
        for (OrderWrapper w : initList) {
            //对每个实现类执行初始化
            w.func.init();
            RecordLog.info(String.format("[InitExecutor] Executing %s with order %d",
                w.func.getClass().getCanonicalName(), w.order));
        }
    } catch (Exception ex) {
        RecordLog.warn("[InitExecutor] WARN: Initialization failed", ex);
        ex.printStackTrace();
    } catch (Error error) {
        RecordLog.warn("[InitExecutor] ERROR: Initialization failed with fatal error", error);
        error.printStackTrace();
    }
}

这里通过SPI机制会去加载META-INF/services/下的com.alibaba.csp.sentinel.init.InitFunc文件获取InitFunc接口的实现类

com.alibaba.csp.sentinel.transport.init.CommandCenterInitFunc
com.alibaba.csp.sentinel.transport.init.HeartbeatSenderInitFunc
com.alibaba.csp.sentinel.metric.extension.MetricCallbackInit

w.func.init()方法会执行每个InitFunc实现类的init()方法,根据InitOrder注解对初始化实现类进行排序,值越小优先级越高,会先执行CommandCenterInitFunc和HeartbeatSenderInitFunc的init方法。

我们先看HeartbeatSenderInitFunc,这个实现类主要完成客户端向服务端注册的心跳发送

public void init() {
    HeartbeatSender sender = HeartbeatSenderProvider.getHeartbeatSender();
    if (sender == null) {
        RecordLog.warn("[HeartbeatSenderInitFunc] WARN: No HeartbeatSender loaded");
        return;
    }

    initSchedulerIfNeeded();
    //心跳发送间隔,默认为10s
    long interval = retrieveInterval(sender);
    setIntervalIfNotExists(interval);
    //启动心跳
    scheduleHeartbeatTask(sender, interval);
}

 private void scheduleHeartbeatTask(/*@NonNull*/ final HeartbeatSender sender, /*@Valid*/ long interval) {
    pool.scheduleAtFixedRate(new Runnable() {//定时发送心跳
        @Override
        public void run() {
            try {
                sender.sendHeartbeat();
            } catch (Throwable e) {
                RecordLog.warn("[HeartbeatSender] Send heartbeat error", e);
            }
        }
    }, 5000, interval, TimeUnit.MILLISECONDS);
    RecordLog.info("[HeartbeatSenderInit] HeartbeatSender started: "
        + sender.getClass().getCanonicalName());
}

这里启动定时任务默认每隔10s发送一次心跳,调用sendHeartbeat方法发送请求

private static final String HEARTBEAT_PATH = "/registry/machine";
public boolean sendHeartbeat() throws Exception {
    if (TransportConfig.getRuntimePort() <= 0) {
        RecordLog.info("[SimpleHttpHeartbeatSender] Runtime port not initialized, won't send heartbeat");
        return false;
    }
    //循环获取连接地址
    InetSocketAddress addr = getAvailableAddress();
    if (addr == null) {
        return false;
    }
    //构建request请求
    SimpleHttpRequest request = new SimpleHttpRequest(addr, HEARTBEAT_PATH);
    //设置请求参数
    request.setParams(heartBeat.generateCurrentMessage());
    try {
        //使用socket发送http请求
        SimpleHttpResponse response = httpClient.post(request);
        if (response.getStatusCode() == OK_STATUS) {
            return true;
        }
    } catch (Exception e) {
        RecordLog.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addr + " : ", e);
    }
    return false;
}

这里发送请求路径为"/registry/machine"到服务端,最终会到达sentinel服务的MachineRegistryController的receiveHeartBeat方法

@ResponseBody
@RequestMapping("/machine")
public Result<?> receiveHeartBeat(String app, @RequestParam(value = "app_type", required = false, defaultValue = "0") Integer appType, Long version, String v, String hostname, String ip, Integer port) {
    if (app == null) {
        app = MachineDiscovery.UNKNOWN_APP_NAME;
    }
    if (ip == null) {
        return Result.ofFail(-1, "ip can't be null");
    }
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    if (port == -1) {
        logger.info("Receive heartbeat from " + ip + " but port not set yet");
        return Result.ofFail(-1, "your port not set yet");
    }
    String sentinelVersion = StringUtil.isEmpty(v) ? "unknown" : v;
    version = version == null ? System.currentTimeMillis() : version;
    try {
        //创建实例,封装信息
        MachineInfo machineInfo = new MachineInfo();
        machineInfo.setApp(app);
        machineInfo.setAppType(appType);
        machineInfo.setHostname(hostname);
        machineInfo.setIp(ip);
        machineInfo.setPort(port);
        machineInfo.setHeartbeatVersion(version);
        //设置心跳时间
        machineInfo.setLastHeartbeat(System.currentTimeMillis());
        machineInfo.setVersion(sentinelVersion);
        //交给appManagement进行管理
        appManagement.addMachine(machineInfo);
        return Result.ofSuccessMsg("success");
    } catch (Exception e) {
        logger.error("Receive heartbeat error", e);
        return Result.ofFail(-1, e.getMessage());
    }
}

public long addMachine(MachineInfo machineInfo) {
    return machineDiscovery.addMachine(machineInfo);
}

private final ConcurrentMap<String, AppInfo> apps = new ConcurrentHashMap<>();

@Override
public long addMachine(MachineInfo machineInfo) {
    AssertUtil.notNull(machineInfo, "machineInfo cannot be null");
    AppInfo appInfo = apps.computeIfAbsent(machineInfo.getApp(), o -> new AppInfo(machineInfo.getApp(), machineInfo.getAppType()));
    appInfo.addMachine(machineInfo);
    return 1;
}

客户端完成注册

深入Sentinel使用和源码分析 Sentinel (分布式系统的流量防卫兵) 是阿里开源的一套用于服务容错的综合性解决方案。它以流量为切入点, 从流量控制、熔断降级、系统负载保护等多个维度来保护服务的稳定性。丰富的应用场景:Sentinel承接了阿里巴巴近 10 年的双十一大促流量的核心场景, 例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。完备的实时监控:Sentinel提供了实时的监控功能。 阅读详情

相关推荐

SpringCloud Alibaba - Sentinel 高级玩法,修改 Sentinel-dashboard 源码,实现 push 模式

前面我们学习了 Sentinel 中的常用玩法,但是在使用的过程中发现一个问题,就是每当我们的服务重启的时候,在 sentinel 控制台上配置的各种规则就都丢失了. 这是因为 sentinel 默认会把这些规则保存到内存中,重启自然就丢失了. 在生产环境中,肯定是不能容忍这种情况的.通过 sentinel 的规则持久化就可解决这个问题.

CYK_byte的博客 2349

Sentinel源码解析-源码环境搭建

本文会讲解如何搭建Sentinel源码调试环境,以方便更好的debug源码,如果对sentinel还不了解的话,可以先参考官方文档:Sentinel官方文档 这里controller提供的两个api都会去调用TestService,我们的流控规则也定义在testService中 这里方法都通过SentinelResource注解来标注成一个资源,并指定了资源名和callback方法和处理BlockException的handler。 我们运行DemoApplication,启动这个demo服务。这里d

ZXMSH的博客 1041

【STM32】H743的25MHZ外部晶振下480MHz时钟的CubeMX配置图

备忘 有时候临时调一个外设做实验需要快速搭建工程的时候,老忘记配置的数据 再补一段代码格式的 void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; /** Supply configuration up

一只爱做笔记的码农 3395

【分布式流控组件 Sentinel 快速入门】——图文详解操作流程

Sentinel是阿里巴巴开源的分布式系统的流量控制组件,旨在保护分布式系统在高并发和故障情况下的稳定性。它提供了实时的流量控制、熔断降级、系统负载保护等功能,是微服务架构中不可或缺的一环。希望本篇博客能够带你一步一步完成Sentinel的入门,从而在微服务架构中有效地保护系统的稳定性和可用性。

仰望天空,妳我亦是行人. 4822

健康保险费用预测:可解释机器学习在精算建模中的实战落地

健康保险费用预测是医疗AI与保险科技交叉领域的核心任务,本质是基于临床变量与社会因素对个体医疗支出进行风险量化。其技术原理需兼顾统计建模能力与监管可解释性,XGBoost+SHAP组合因支持特征归因、边际效应分析和临床可干预推演,成为保险精算场景的主流选择。该技术显著提升保费定价精度、降低偿付风险,并支撑DRG费用预警、团险核保辅助及再保险尾部风险评估等关键应用。本文聚焦真实产线中的时间序列验证、临床分层特征工程与监管红线指标(如Bias@90th、Calibration Slope),深入解析如何让模型不

weixin_33702545的博客 306

FOC观测器之龙伯格观测器

状态观测器: 理论依据:根据控制理论,如果一个系统能够完全通过其检测到的输出值来重构其系统状态,则认为该系统是可观测的。其作用于无传感器转子的位置和速度的检测反馈,再作用到PARK逆变换和转矩磁链控制上。 Luenberger观察器原理图: Luenberger观测器的离散化: (其观测器的闭环参数为经验验证值) 引入估测电流( iα,iβ )的反馈值并离散化(T 为采样时间),可得...

ShawnChan的博客 2万+

Sentinel核心架构源码剖析(上)

1. sentinel客户端与服务端通信原理 2. 注解@SentinelResource核心源码剖析 3. Sentinel数据规则校验责任链设计模式详解 4. sentinel限流降级核心源码剖析 5. sentinel新版本熔断器核心源码剖析 6. sentinel资源授权与系统规则校验源码剖析 pom引入 <dependency> <groupId>com.alibaba.cloud</groupId> <artifactI

hc1428090104的博客 561

量化交易新手必看:如何用Python快速接入XTP极速交易系统(附避坑指南)

本文为量化交易新手提供了使用Python快速接入中泰证券XTP极速交易系统的完整指南。文章详细介绍了XTP系统的微秒级性能优势、与CTP系统的核心区别,并逐步讲解了环境配置、API连接、资金查询、下单撤单等关键步骤,同时分享了网络维护、订单处理等实战避坑技巧,帮助开发者高效对接专业交易柜台。

life6的博客 659

sentinel原理源码分析系列(三)-启动和初始化

本文是sentinel原理源码分析系列第三篇,分析sentinel启动和初始化。

leehom的博客 791

NV 英伟达2022数字芯片笔试题

作者:数字IC打工人 链接:【开卷】第27期 NV 英伟达2022数字芯片笔试题_笔经面经_牛客网 来源:牛客网 1、Single Choice: Given thefollowing FIFO and rules, how deep does the FIFO need to be to preventunderflow or overflow? RULES: clk_A=25MHz; clk_B=100MHz; en_B is periodically asserted: period.

weixin_44072819的博客 6386

PointPainting 复现

三维目标检测

weixin_58207716的博客 4532

Java高级面试与工程实践核心问题解析

Java作为企业级应用开发的主流语言,其高级特性和工程实践是开发者进阶的关键。本文从Spring框架的循环依赖解决、JVM性能调优到分布式系统设计,深入探讨了Java工程实践中的核心问题。通过分析Spring三级缓存机制、G1垃圾回收器优化等热词技术,揭示了Java在高并发、分布式场景下的技术价值。文章特别针对分布式锁选型、缓存穿透防御等高频搜索问题,提供了工业级解决方案,适合中高级开发者提升系统设计能力和面试准备。

weixin_30608503的博客 331

【docker】--- 详解 WSL2 中的 Ubuntu 和 Docker Desktop 的区别和关系!

在编程的艺术世界里,代码和灵感需要寻找到最佳的交融点,才能打造出令人为之惊叹的作品。而在这座秋知叶i博客的殿堂里,我们将共同追寻这种完美结合,为未来的世界留下属于我们的独特印记。

秋知叶i 1314

SpringCloud Alibaba微服务中Sentinel流控规则(详解+示例demo+测试效果)

前言: 本篇博客介绍了有关于Sentinel的几种常用的流控规则。 文章目录一。概述二。QPS-直接-快速失败三。线程-直接-快速失败四。QPS-关联-快速失败五。QPS-链路-快速失败六。QPS-预热-快速失败七。QPS-匀速排队-快速失败 一。概述 流量控制(flow control),其原理是监控应用流量的 QPS 或并发线程数等指标,当达到指定的阈值时对流量进行控制,以避免被瞬时的流量高峰冲垮,从而保障应用的高可用性。 FlowSlot 会根据预设的规则,结合前面 NodeSelectorSlo

爱吃鸡腿的明仔 958

[Python图像处理] 十九.图像分割之基于K-Means聚类的区域分割

前面的文章讲解了图像锐化和边缘提取技术,该篇文章将开始围绕图像分割进行讲解。图像分割就是把图像分成若干个特定的、具有独特性质的区域并提出感兴趣目标的技术和过程。 本篇文章主要讲解基于理论的图像分割方法,通过K-Means聚类算法实现图像分割或颜色分层处理。基础性文章,希望对你有所帮助。 1.K-Means原理 2.K-Means聚类分割灰度图像 3.K-Means聚类对比分割彩色图像

杨秀璋的专栏 4万+

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Sentinel 控制台使用和源码

通过阅读和理解 Sentinel 控制台的源码,不仅可以深入学习其内部机制,还能根据实际需求对其进行定制和扩展。Sentinel 控制台是用于管理和配置 Sentinel 系统规则的可视化界面。:定义了资源、规则等数据结构以及相关的业务逻辑处理代码,例如解析和生成流量控制、熔断降级等规则。:基于 Vue.js 实现的交互式管理页面,负责展示和操作各项配置信息。

qq_33240556的博客 447

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Sentinel

Sentinel能在项目中干什么 Sentinel官方文档链接:https://gitee.com/rmlb/Sentinel/wikis/%E4%B8%BB%E9%A1%B5?sort_id=3419413 当前博客内容根据SpringCloud环境编写,非SpringCloud环境使用Sentinel参考官方文档。 1、简介 Sentinel是阿里开源的项目,提供了流量控制、熔断降级、系统负载保护等多个维度来保障服务之间的稳定性。 2、特征 a、应用场景丰富; b、完备的实时监控:Sent

好记性不如烂笔头 1003

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

SpringCloud Sentinel 使用

在以后我们的项目部署上线的时候,会有各种各样的服务突发问题,比如雪崩效应(在分布式系统中,由于网络原因或自身的原因,服务一般无法保证 100% 可用。如果一个服务出现了问题,调用这个服务就会出现线程阻塞的情况,此时若有大量的请求涌入,就会出现多条线程阻塞等待,进而导致服务瘫痪。由于服务与服务之间的依赖性,故障会传播,会对整个微服务系统造成灾难性的严重后果,这就是服务故障的雪崩效应)等问题。

程序猿追的博客 6754

入门sentinel

资源定义:在Sentinel中,资源是指需要被保护的微服务中的某个点,如HTTP接口、RPC调用、数据库操作等。这些资源通过Sentinel提供的API或注解进行定义,并赋予一个唯一的名称(resourceName)。资源注册:定义好的资源会被注册到Sentinel中,Sentinel会为每个资源创建相应的统计节点(如DefaultNode、ClusterNode等),用于保存该资源的各类统计信息(如QPS、异常数量等)。在Spring Boot应用中,你可以通过多种方式定义需要Sentinel保护的资源。

m0_63550220的博客 1236

Sentinel详细使用步骤

服务熔断,当某服务出现不可用或响应超时的情况时,为了防止整个系统出现雪崩,暂时停止对该服务的调用。停止是说,当前服务一旦对下游服务进行熔断,当请求到达时,当前服务不再对下游服务进行调用,而是使用设定好的策略(如构建默认值)直接返回。暂时是说,熔断后,并不会一直不再调用下游服务,而是以一定的策略(如每分钟调用 10 次,若均返回成功,则增大调用量)试探调用下游服务,当下游服务恢复可用时,自动停止熔断。随着微服务的流行,服务和服务之间的稳定性变得越来越重要。

Ivyvivid的博客 3409

springcloud-alibaba sentinel 简单入门二

这一节我们是对sentinel进行配置,添加流控信息;我们将我们的服务注册到我们sentinel中在我们簇点链路中会有我们的接口名称,在我们对应的接口名称旁边也就有我们的流控按钮进行操作;我们点击这个按钮会有以下弹窗 当我们选择qps会让我们填写单机阈值; 比如我们填写1的话,也就是说再我们这一秒期间只能有一个来访问其他就是被我们sentinel进行阻塞,其他则进行以下操作比如流控模式是选择直接的话,然后流控效果是快速失败的话,那么我们一秒中只能有一个请求成功,其他则返回失败如果我们选址不是qps而是并发

xc_blog 433

Sentinel源码—1.使用演示和简介一

如果队列中的请求超过一定数量或者等待时间超过一定阈值,则直接拒绝新的请求,从而避免服务器的过载。接着,在Dashboard上建立一个资源名为testQps的流控规则,也就是针对testQps这个资源建立一个QPS为1的流控配置。也就是如果超出了配置的阈值,则会等待1秒钟,而不是直接拒绝,从而尽可能保证不丢失用户的请求。也就是testOrder被流控的时机就是当testPay的QPS达到3的时候,3并不是testOrder所访问的次数,而是testPay接口被访问的次数。

mjunz的博客 1218

spring cloud注册不上sentinel问题

直接运行java -jar sentinel-dashboard-1.8.6.jar。配置spring cloud alibaba。工程构件采用的是maven,父pom的配置。启动user应用后查看控制台。// 该配置保证启动立即注册。新建一个order服务。

ilwoziji的博客 2130

Sentinel的启动与运行

1.首先去Sentinel官网下载sentinel-dashboard-版本号.jar https://github.com/alibaba/Sentinel/releases 2.将下载后的sentinel.jar放在本地非中文目录下; 并在和jar同级目录下,打开cmd窗口;然后,执行下述命令; java -jar sentinel-dashbord-1.8.2.jar 打开浏览器,输入http://localhost:8080/ 用户名和密码都是 sentinel 若想以指定端口运行,怎在运行

总结复盘,才能不迷失自己! 9950

Sentinel快速入门—启动 Sentinel 控制台+微服务快速引入Sentinel

Sentinel是阿里巴巴开源的一款微服务流量控制组件。官网地址: https://sentinelguard.io/zh-cn/index.htm。注意: sentinel-dashboard.jar的名字需要和末尾的名字相同。(通过执行当前模块的代码后)即可在控制台导航区看见引入的模块。在配置文件application.yml中添加以下内容。进入登入页面后账号密码都为:sentinel。如果您的应用使用了 Maven,则在。具体参数配置可以点击查看当前链接。其他模块也是相同引入方式。

cjyyan的博客 1541

微服务保护之Sentinel安装、配置流控规则、流控效果详解、热点参数限流、线程隔离与熔断降级详细配置、访问请求授权、自定义异常处理超详细,学会Sentinel一篇足矣

默认情况下,发生限流、降级、授权拦截时,都会抛出异常到调用方。如果要自定义异常时的返回结果,需要实现/**处理请求被限流、降级、授权拦截时抛出的异常:*/voidthrowsException;而包含很多个子类,分别对应不同的场景异常说明限流异常热点参数限流的异常降级异常授权规则异常系统规则异常所以我们需要在中定义类,实现接口:@Component@OverrideString msg = "未知异常";msg = "请求被限流了!

weixin_64339548的博客 3560
上一篇: netty源码浅析-池化内存PoolThreadCache分配
下一篇: sentinel源码分析-02客户端处理服务端下发请求
胖柯G
博客等级 码龄10年 453粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值