OpenFeign集成Sentinel实现服务的熔断降级

OpenFeign的降级配置 OpenFeign的降级配置前言OpenFeign的基本使用OpenFeign设置降级 前言 当我们需要调用其他微服务或者第三方接口时,我们可能会使用Dubbo或者Spring自带的组件RestTemplate,但相对于前面两位来说 我还是比较喜欢使用SpringCloud的组件Feign的,在我看来Feign的使用还是比较灵活的。 OpenFeign的基本使用 懒得自己写一个微服务,这里我在网上搜了一个第三方接口: https://api.imjad.cn/cloudmusic/?type=song&a 阅读详情

引入依赖

Feign 适配整合在 Spring Cloud Alibaba 中,所以我们直接引入spring cloud alibaba中的组件就好

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

除此之外,我们还需要引入OpenFeign和Nacos的依赖

        <!--添加loadbalancer依赖
            由于 Netflix Ribbon 进入停更维护阶段,因此 SpringCloud 2020.0.1 版本之后 删除了eureka中的ribbon,
            替代ribbon的是spring cloud自带的LoadBalancer,默认使用的是轮询的方式
            新版本的 Nacos discovery 都已经移除了 Ribbon ,此时我们需要引入 loadbalancer 代替,才能调用服务提供者提供的服务
        -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

生产者接口

在配置消费者之前,我们需要先编写好生产者的相关代码,这里引用之前的user-service,不再赘述,只贴出一些核心代码,完整的源码可以在gitee或者github上找到,文末会给出仓库地址

package cuit.epoch.pymjl.controller;
​
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import cuit.epoch.pymjl.entity.User;
import cuit.epoch.pymjl.exception.AppException;
import cuit.epoch.pymjl.result.CommonResult;
import cuit.epoch.pymjl.result.ResultUtils;
import cuit.epoch.pymjl.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
​
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicInteger;
​
/**
 * @author Pymjl
 * @version 1.0
 * @date 2022/8/25 12:48
 **/
@RestController
@RequestMapping("/user")
@Log4j2
public class UserController {
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);
​
    @Resource
    UserService userService;
​
    @Value("${server.port}")
    private String port;
​
    @GetMapping("/test")
    @SentinelResource(value = "test", blockHandler = "handleTest")
    public CommonResult<String> test(HttpServletRequest request) throws UnknownHostException {
        System.out.printf("被[/%s:%s]调用了一次%n", request.getRemoteHost(), request.getRemotePort());
        String hostAddress = InetAddress.getLocalHost().getHostAddress() + ":" + port;
        return ResultUtils.success(hostAddress);
    }
​
    @GetMapping("/register")
    @SentinelResource("register")
    public CommonResult<String> register() {
        userService.register();
        return ResultUtils.success();
    }
​
    @GetMapping("/get/{id}")
    @SentinelResource(value = "getUser")
    public CommonResult<User> get(@PathVariable("id") Long id) {
        int cnt = ATOMIC_INTEGER.incrementAndGet();
        log.info("cnt=={}", cnt);
        if (cnt % 2 == 0) {
            throw new AppException("发生了异常");
        }
        return ResultUtils.success(userService.get(id));
    }
​
    public CommonResult<String> handleTest(HttpServletRequest request, BlockException blockException) {
        log.error("调用/user/test失败");
        return ResultUtils.fail("Sentinel流控,调用失败");
    }
​
}
​

配置消费者

这里我们结合着Sentinel控制台进行演示,所以我们需要先配置控制台的相关信息,在消费者的bootstrap.yaml 中如下配置

spring:
  application:
    name: user-openfeign-consumer
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.199.128:8848 #Nacos地址
      config:
        server-addr: 192.168.199.128:8848 #Nacos地址
        file-extension: yaml #这里我们获取的yaml格式的配置
    #sentinel控制台
    sentinel:
      transport:
        #配置 Sentinel dashboard 地址
        dashboard: 192.168.199.128:8858
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
​
#开启sentinel的支持
feign:
  sentinel:
    enabled: true

我们还需要在主启动类上添加注解,开启对OpenFeign的支持

package cuit.epoch.pymjl;
​
import cuit.epoch.pymjl.config.OpenFeignConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
​
/**
 * @author Pymjl
 * @version 1.0
 * @date 2022/8/31 23:37
 **/
@SpringBootApplication
@EnableFeignClients(defaultConfiguration = OpenFeignConfig.class)
public class OpenFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(OpenFeignApplication.class, args);
    }
}
​
/**
 * 在启动类的注解@EnableFeignClients上指定
 * 局部生效就在@FeignClient中指定,不能加@Configuration注解
 *
 * @author Pymjl
 * @version 1.0
 * @date 2022/9/1 13:17
 **/
public class OpenFeignConfig {
    @Bean
    public Logger.Level feignLogLevel() {
        // 日志级别为BASIC
        return Logger.Level.FULL;
    }
}

service接口

package cuit.epoch.pymjl.service;
​
import cuit.epoch.pymjl.entity.User;
import cuit.epoch.pymjl.feign.FeignServiceFallback;
import cuit.epoch.pymjl.result.CommonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
​
/**
 * @author Pymjl
 * @version 1.0
 * @date 2022/9/1 0:03
 **/
@FeignClient(value = "user-service", fallback = FeignServiceFallback.class)
public interface UserFeignClient {
    /**
     * 注册
     *
     * @return {@code CommonResult<String>}
     */
    @GetMapping("/user/register")
    CommonResult<String> register();
​
    /**
     * 得到
     *
     * @param id id
     * @return {@code CommonResult<User>}
     */
    @GetMapping("/user/get/{id}")
    CommonResult<User> get(@PathVariable("id") Long id);
}

编写降级异常处理类

package cuit.epoch.pymjl.feign;
​
import cuit.epoch.pymjl.constant.ResultEnum;
import cuit.epoch.pymjl.entity.User;
import cuit.epoch.pymjl.result.CommonResult;
import cuit.epoch.pymjl.result.ResultUtils;
import cuit.epoch.pymjl.service.UserFeignClient;
import org.springframework.stereotype.Component;
​
/**
 * @author Pymjl
 * @version 1.0
 * @date 2022/9/17 22:06
 **/
@Component
public class FeignServiceFallback implements UserFeignClient {
    @Override
    public CommonResult<String> register() {
        return ResultUtils.fail(ResultEnum.SENTINEL_FALLBACK_ERROR);
    }
​
    @Override
    public CommonResult<User> get(Long id) {
        return ResultUtils.fail(ResultEnum.SENTINEL_FALLBACK_ERROR);
    }
}
​

测试

接下来,启动项目,进行测试。我们先调用消费者的接口,然后可以在控制台中Sentinel看到

然后我们添加如图所示的降级规则:

随后我们对接口进行测试访问:

如图所示,当请求次数为偶数时就会抛出异常,然后服务进行降级,生产者代码逻辑如下:

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

    @GetMapping("/get/{id}")
    @SentinelResource(value = "getUser")
    public CommonResult<User> get(@PathVariable("id") Long id) {
        int cnt = ATOMIC_INTEGER.incrementAndGet();
        log.info("cnt=={}", cnt);
        if (cnt % 2 == 0) {
            throw new AppException("发生了异常");
        }
        return ResultUtils.success(userService.get(id));
    }

当请求次数为奇数时就可以正常访问

然后当我们快速连续的访问多次该接口以后,服务会根据我们配置的降级规则,Sentinel会对服务进行熔断,熔断后无论请求次数为奇数还是偶数,请求都会被拒绝,只有等熔断时长过了后才有可能恢复服务

小结

总之,因为Spring Cloud Alibab已经集成了Sentinel,所以我们使用Spring Cloud来集成Sentinel非常方便,总结下来就这几个步骤:

  1. 引入对应的依赖
  2. 开启Sentinel支持
  3. 编写FeignClient,并为FeignClient指定对应的降级处理类
  4. 编写对应的降级异常处理类,该类需要实现FeignClient
最新版 !快速掌握 JDK17 + springboot3 + springcloud Alibaba : 5、服务熔断降级 Sentinel 官网:https://sentinelguard.io/zh-cn/index.htmlSentinel (分布式系统的流量防卫兵) 是阿里开源的一套用于服务容错的综合性解决方案。它以流量为切入点, 从流量控制、熔断降级、系统负载保护等多个维度来保护服务的稳定性丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景, 例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。完备的实时监控。 阅读详情

相关推荐

12.springCloud AlibabaSentinel实现熔断与限流

Sentinel是阿里巴巴开源的一款面向分布式、多语言异构化服务架构的流量治理组件,提供流量控制、熔断降级、系统保护等功能。其核心功能包括: 流量治理:支持QPS限流、线程数限流、热点参数限流等多种策略,可防止系统被突发流量击垮。 熔断降级:通过慢调用比例、异常比例等策略自动熔断不稳定服务,避免级联故障。 系统保护:根据系统负载(CPU、RT等)动态调整流量入口,保障系统稳定性。 Sentinel特色: 生产验证:支撑阿里双十一大促核心场景 多语言支持:提供Java/Go/C++/Rust等实现 丰富生态:

麒麟阁 1085

OpenFeign实现降级

OpenFeign实现降级

Leon_Jinhai_Sun的博客 3119

(七)Sentinel整合OpenFeign--降级熔断

Sentinel整合OpenFeign--降级熔断 消费端调用生产端,如果生产端服务挂掉了,那么消费端调用的时候就会报500错误,启用熔断器,返回的信息会更优化 实现 第一步: 定义fallback类,当熔断时返回默认数据 package com.ifly.orderservice.client.fallback; import com.ifly.common.ResultInfo; import com.ifly.feign.vo.ProductInfo; import com.ifly....

专搞技术的小兔子 880

【PmHub后端篇】PmHub集成 Sentinel+OpenFeign实现网关流量控制与服务降级

本文围绕 PmHub,介绍 Sentinel 在微服务架构中熔断降级的必要性、基本概念、原理等,阐述其下载使用方法,以及配合 Gateway 实现网关限流、配合 OpenFeign 实现自定义 fallback 服务降级,助力开发者保障微服务架构稳定性。

专注Java和MySQL领域知识分享 1407

springCloud/Alibaba常用中间件之Setinel实现熔断降级

在上述的过程中大家应该已经发现了每当重启的时候都要重新进行配置Sentinel,这时就需要持久化配置,但是Sentinel并没有自带持久化功能,需要结合Nacos才可以完成,所以在这里在从述一下,这里的Sentinel版本要1.8以上,且三者的关系一定不要有依赖冲突。

weixin_68576312的博客 1378

CH340驱动安装全攻略:从Windows到MacOS的避坑指南(2025最新版)

本文提供2025年最新版CH340驱动安装全攻略,涵盖Windows、MacOS和Linux三大操作系统。详细解析了驱动安装的核心原理、标准流程,并针对Windows设备管理器报错、MacOS系统安全限制等常见“坑点”提供了深度排错与解决方案,旨在帮助开发者快速稳定地完成USB转串口通信配置。

earth的博客 428

08-OpenFeign-结合Sentinel,实现熔断降级

当我们在对服务远程调用时,会因为服务的请求超时、抛出异常等情况,导致调用失败。如果短时间内,产生大量请求异常。引发上游的调用方请求积压,最终会引起整个调用链雪崩。为此我们需要对核心的调用过程进行监控,当产生异常时,可以采取相应的措施,确保服务的容错性、可用性。OpenFeign默认支持Hystrix,本文主要以alibaba 相关中间件为参考。服务调用方以下配置结合了spring cloud、spring boot、spring cloud-alibaba。具体的接入可以。

宣晨光 2349

LeGO-LOAM相对LOAM的改进---地面分离的方法-算法原理+代码讲解

实际上此种地⾯分离算法有⼀些简单,我们可以结合激光雷达安装⾼度等其他先验信息进⾏优化,避免将桌子这些当作地面点。LeGO-LOAM中前端改进中很重要的⼀点就是充分利⽤了地⾯点,那⾸先⾃然是提取对地⾯点的提取。理想情况下, 应该接近0,考虑到⼀⽅⾯激光雷达安装也⽆法做到绝对⽔平,另⼀⽅⾯,地⾯也不是绝。对⽔平,因此,这个⾓度会略微⼤于0,考虑到作者实际在草坪之类的场景下运动,因此这个值被设置成。如上图,相邻的两个扫描线束的同⼀列打在地⾯上如AB点所⽰,他们的垂直⾼度差。,计算垂直⾼度差和⽔平⾼度差的⾓度。..

zysss_的博客 776

八.SpringCloudAlibaba极简入门-Sentinel兼容Feign进行服务熔断

老鸟飞过 , 只做学习使用,欢迎交流 1.概述 Spring Cloud Alibaba是Spring Cloud的一个子项目,OpenFeign是Spring Cloud的客户端负载均衡器,使用Spring Cloud Alibaba依然可以很方便的集成OpenFeign,如果要使用OpenFeign作为服务客户端负载均衡,那么我们需要考虑OpenFeign开启Sentinel进行服务熔断降级。...

墨家巨子@俏如来 2921

37、半导体硅材料中的缺陷与吸杂技术解析

本文系统解析了半导体硅材料中的缺陷形成机制及其对电子器件性能的影响,重点探讨了生长和工艺诱导缺陷、表面与内部微缺陷的起源与特征。文章详细阐述了吸杂技术的原理、过程及在集成电路和太阳能电池制造中的应用,强调通过氧行为调控和热处理优化实现缺陷控制。同时介绍了吸杂效果的评估方法,并展望了未来新型吸杂技术的发展趋势,为提升半导体器件性能和制造良率提供理论支持和技术路径。

mongodb5scout的博客 164

ximalaya 新xm-sign逆向思路

本文主要介绍目标网站新xm-sign值的逆向思路。仅代表个人理解,如有其他建议可在评论区沟通。声明仅仅记录一下自己的学习方法,不作为其他参考、更不作为商业用途。如有侵犯请联系本人删除。

weixin_66580433的博客 2017

OpenFeign 全方位讲解

2、Feign是什么? Feign也是一个狠角色,Feign旨在使得Java Http客户端变得更容易。 Feign集成了Ribbon、RestTemplate实现了负载均衡的执行Http调用,只不过对原有的方式(Ribbon+RestTemplate)进行了封装,开发者不必手动使用RestTemplate调服务,而是定义一个接口,在这个接口中标注一个注解即可完成服务调用,这样更加符合面向接口编程的宗旨,简化了开发。 但遗憾的是Feign现在停止迭代了,当然现在也是有不少企业在用。 有想要学习Feign的.

LoveSummer 2万+

美团mtgsig 1.2算法分析

mtgsig1.2的一些算法总结

记录一些web逆向的过程 3506

SpringCloudAlibaba:Sentinel

Sentinel能够对流量进行控制,主要是监控应用的QPS流量或者并发线程数等指标,如果达到指定的阈值时,就会被流量进行控制,以避免服务被瞬时的高并发流量击垮,保证服务的高可靠性。参数见最下方:1资源名资源的唯一名称,默认就是请求的接口路径,可以自行修改,但是要保证唯一。2针对来源具体针对某个微服务进行限流,默认值为default,表示不区分来源,全部限流。3阈值类型QPS表示通过QPS进行限流,并发线程数表示通过并发线程数限流。4单机阈值与阈值类型组合使用。

2301_79526467的博客 1179

【MATLAB代码】UKF组合导航例程,15维状态量、3维观测量。附完整的代码,有中文注释、误差输出图像

摘要 本文提出了一种基于15维误差状态模型的UKF组合导航算法,实现了三维位置、速度和姿态的高精度估计。算法采用严格的误差状态模型,包含位置(3)、速度(3)、姿态(3)、陀螺偏差(3)和加速度计偏差(3)共15个状态量,通过3维GNSS位置观测进行校正。仿真结果表明,相比纯IMU积分,UKF算法能有效抑制误差积累,显著提高导航精度。文中提供了完整的MATLAB源代码,可直接运行并复现三维轨迹对比、位置/速度曲线及误差分析结果。

985工科博士毕业,专攻定位、导航和滤波等算法研究。从业10年,主要使用MATLAB 312

华为od统一考试B卷【宜居星球改造计划】Java&Go 实现

XXX年,人类通过对火星的大气进行宜居改造分析,使得火星已在理论上具备人类宜居的条件,由于技术原因,无法一次性将火星大气全部改造,只能通过局部处理形式,假设将火星待改造的区域为row * column的网格每个网格有3个值,宜居区、可改造区、死亡区,使用YES、NO、NA代替,YES表示该网格已经完成大气改造,NO表示该网格未进行改造,后期可进行改造,NA表示死亡区,不作为判断是否改造完成的宜居,无法穿过 初始化下,该区域可能存在多个宜居区,并且每个宜居区能同时在每个太阳日单位向上下左右四个方向的相邻格子进

MISAYAONE的博客 1万+

SpringCloud框架学习(第六部分:Sentinel实现熔断与限流)

等价于 Spring Cloud Circuit BreakerSentinel 能够对流量进行控制,主要是监控应用的 QPS 流量或者并发线程数等指标,如果达到指定的阈值时,就会被流量进行控制,以避免服务被瞬时的高并发流量击垮,保证服务的高可靠性。1资源名资源的唯一名称,默认就是请求的接口路径,可以自行修改,但是要保证唯一。2针对来源具体针对某个微服务进行限流,默认值为default,表示不区分来源,全部限流。3阈值类型QPS表示通过QPS进行限流,并发线程数表示通过并发线程数限流。4单机阈值。

xpy2428507302的博客 2133

uniapp [全端兼容] - 详细实现人脸识别和活体检测功能,实时监测人脸是否进入区域及动作是否正确播报,免费自动提示引导动作及语音,提供提供实名认证、身份证识别、人脸信息采集、刷脸扫脸认证示例代码

uniapp,h5移动端网页,微信小程序,支付宝小程序,Android安卓,苹果ios,app,nvue,人脸识别,扫脸认证,人脸认证,活体认证,身份认证,uni-app人脸识别详细教程,如何在app端实现免费人脸识别教程,如何在小程序端做,最好用的插件,安卓ios百度人脸识别、活体检测、人脸采集APP,H5人脸识别带前后摄像头,适合新手看的人脸识别功能教程,详细示例代码源码,有没有免费的,接入百度,阿里云人脸识别,百度,api,活体检测,数据采集,动作提示指引,语音提示指引,报错,无法核验一直出错,根本用

🏆 前端领域优质创作者 1万+

微服务之.SpringCloud AlibabaSentinel实现熔断与限流

Sentinel中的断路器不仅可以统计某个接口的慢请求比例,还可以统计异常请求比例。当这些比例超出阈值时,就会熔断该接口,即拦截访问该接口的一切请求,降级处理;当该接口恢复正常时,再放行对于该接口的请求。断路器的工作状态切换有一个状态机来控制:closed:关闭状态,断路器放行所有请求,并开始统计异常比例、慢请求比例。超过阈值则切换到open状态open:打开状态,服务调用被熔断,访问被熔断服务的请求会被拒绝,快速失败,直接走降级逻辑。Open状态持续一段时间后会进入half-open状态。

qq_62377885的博客 3201

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

5-SpringCloudAlibaba整合Sentinel

springcloudalibaba整合sentinel

cl617287的博客 1990

深度学习工具包 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")

SpringCloud Alibaba学习(六)——Sentinel服务熔断OpenFeign

简介 之前的操作,一直使用的 RestTemplate,虽然很好用,但是并不适合后期的开发使用。 请求参数变更,需要不断的在url后拼接或者修改对应的请求name信息。 OpenFeign的基本使用

专注写bug 769

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

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

【手把手教你搭建SpringCloud 12】集成Sentinel流量防护与熔断降级策略

本文介绍了在Spring Cloud微服务架构中集成Alibaba Sentinel进行流量防护和熔断降级的实践方案。通过对比Sentinel与Hystrix的技术优势,详细讲解了Sentinel Dashboard的部署配置方法,以及Spring Cloud Alibaba集成Sentinel的项目结构设计和依赖配置。文章重点包括:1)Sentinel与Hystrix的技术对比分析;2)Sentinel Dashboard的容器化部署方式;3)Spring Cloud项目集成Sentinel的具体实现步骤

专注后端技术架构,AI技术分享 1105

SpringCloud Alibaba之Sentinel集成Ribbon/OpenFeign案例演示

Sentinel集成Ribbon: 1、准备服务提供者cloudalibaba-nacos-provider-payment9001,cloudalibaba-nacos-provider-payment9002,主要是端口不一样,其他一致,下面附上pom、yml和主业务类代码,这里自己建module即可 <!--SpringCloud ailibaba nacos --> <dependency> <groupId&

TOP__ONE的博客 1768

SpringCloud源码探析(九)- Sentinel概念及使用

在微服务的依赖调用中,若被调用方出现故障,出于自我保护的目的,调用方会主动停止调用,并根据业务需要进行对应处理,这种方式叫做熔断,是微服务的一种保护方式。为了保证服务的高可用性,springcloud中有专门的流量管控组件,负责熔断、限流和降级。springcloud中较为知名的熔断器有Hystrix和Sentinel,本文将分析Sentinel的优势及其使用。

qq_33479841的博客 1340
上一篇: 【数据结构与算法】List接口&栈&队列
下一篇: Spring Cloud Gateway集成Sentinel流控
Java技术那些事儿
博客等级 码龄5年 2306粉丝 2584原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值