第三章 SpringBoot高级话题

SpringBoot高级-底层原理 这是一个关于SpringBoot自动化配置原理的博文,包括了starter依赖管理机制、自动化配置初体验、底层原理等多方面的内容。此外,还有SpringBoot健康监控的相关内容,如健康监控服务和Admin可视化。 阅读详情

1.Spring Aware

1. 点睛

1.1 Spring依赖注入最大的亮点是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器,这时Bean之间的耦合度很低。
1.2 但是实际项目中,不可避免用到Spring容器本身的功能资源,这时你的Bean必须要意识到Spring容器的存在,才能调用Spring所提供的资源,即所谓的Spring Aware;
1.3 其实Spring Aware本身就是Spring设计用来框架内部使用的,使Bean和Spring框架耦合。

在这里插入图片描述

1.4 Spring Aware目的是为了让Bean获得Spring容器服务。因为ApplicationContext接口集成了MessageSource接口,ApplicationEventPublisher接口和ResourceLoader接口,所以Bean继承ApplicationContextAware可以获得Spring容器所有的服务,但原则上用到啥接口就实现啥接口。

2. 示例

2.1 新建test.txt供外部资源加载使用

2.2 演示类:

代码解释:
实现BeanNameAware, ResourceLoaderAware,获得Bean名称和资源加载的服务;
BeanNameAware—>重写setBeanName();
ResourceLoaderAware—>重写setResourceLoader()

package com.leonard2;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import sun.misc.IOUtils;
import sun.nio.ch.IOUtil;

import java.io.IOException;
@Service
public class AwareService implements BeanNameAware, ResourceLoaderAware {
    private String beanName;
    private ResourceLoader loader;
    @Override
    public void setBeanName(String s) {
        this.beanName = s;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.loader = resourceLoader;
    }

    public void  outputResult(){
        System.out.println("bean的名称"+beanName);
        Resource resource = loader.getResource("com/leonard2/test.txt");
        try {
            System.out.println("Loader加载的文件内容为:"+resource.getInputStream());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

2.3 配置类

@Configuration
@ComponentScan("com.leonard2")
public class AwareConfig {
}

2.4 运行类

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class);
        AwareService bean = context.getBean(AwareService.class);
        bean.outputResult();
        context.close();
    }
}

2.多线程

1.点睛

Spring通过任务执行器(TaskExwcutor)实现多线程和并发编程;
使用ThreadPoolTaskExecutor实现一个基于线程池的TaskExecutor;
实际开发一般都是异步的,所有需要在配置类中通过@EnableAsync开启异步任务支持,并且需要在实际执行的Bean方法使用@Async注解声明其是一个异步任务

2.示例

2.1 配置类 TaskExecutorConfig

@EnableAsync//注解开启异步任务支持
配置类实现AsyncConfigurer 重写getAsyncExecutor();
返回ThreadPoolTaskExecutor,获得基于线程池的TaskExecutor;

package com.leonard3;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author Leonard.Z
 * @date 2020/9/24  17:36
 * @des 配置类实现AsyncConfigurer 重写getAsyncExecutor();
 * 返回ThreadPoolTaskExecutor,获得基于线程池的TaskExecutor
 */

@Configuration
@ComponentScan("com.leonard3")
@EnableAsync//注解开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}

2.2 任务执行类 AsyncTaskService

通过@Async注解声明该方法是异步方法;
如果注解在类级别,则代表该类所有方法都是异步方法;
这里的方法自动被注入使用【ThreadPoolTaskExecutor】作为【TaskExecutor】

package com.leonard3;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author Leonard.Z
 * @date 2020/9/24  17:46
 * @des  任务执行类
 */
@Service
public class AsyncTaskService {
    @Async
    public void executeAsyncTask(Integer i){
        System.out.println("执行异步任务:"+i);
    }
    @Async
    public void executeAsyncTask2(Integer i){
        System.out.println("执行异步任务+1:"+(i+1));
    }
}

2.3 运行

执行结果是并发执行而不是顺序执行

执行异步任务:0
执行异步任务:1
执行异步任务:2
执行异步任务+1:2
执行异步任务:4
执行异步任务+1:5
执行异步任务+1:1
执行异步任务:5
执行异步任务:6
执行异步任务+1:4
执行异步任务:3
执行异步任务+1:3
执行异步任务+1:8
执行异步任务:7
执行异步任务+1:7
执行异步任务+1:6
执行异步任务+1:10
执行异步任务:9
执行异步任务+1:9
执行异步任务:8

package com.leonard3;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Leonard.Z
 * @date 2020/9/24  17:49
 * @des  Main
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
        AsyncTaskService ser = context.getBean(AsyncTaskService.class);
        for (int i = 0; i < 10; i++) {
            ser.executeAsyncTask(i);
            ser.executeAsyncTask2(i);
        }
        context.close();
    }
}

3.计划任务

1.点睛

  1. 在配置类注解@EnableScheduling开启对计划任务的支持;
  2. 在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。
    【@Scheduled】支持多种类型计划任务,包括【cron】,【fixDelay】,【fixRate】

2.示例

2.1 计划任务执行类 ScheduleTaskServcie

【@Scheduled】 声明该方法是个计划任务,使用【fixedRate】属性每隔固定时间执行
【cron】属性按照固定时间执行,本例指每天11点28分执行

package com.leonard4;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Leonard.Z
 * @date 2020/9/26  10:17
 * @des  计划任务执行类
 * @Scheduled 声明该方法是个计划任务,使用fixedRate属性每隔固定时间执行
 *              cron属性按照固定时间执行,本例指每天11点28分执行
 */
@Service
public class ScheduleTaskServcie {
    private static final SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void rptCurrentTime(){
        System.out.println("每隔五秒执行一次:"+fmt.format(new Date()));
    }
    @Scheduled(cron = "0 14 16 ? * *")
    public void fixTimeExecution(){
        System.out.println("在指定时间"+fmt.format(new Date())+"执行");
    }
}

2.2 配置类 :ScheduleTaskConfig

通过【@EnableScheduling】 开启对计划任务的支持

package com.leonard4;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author Leonard.Z
 * @date 2020/9/26  10:46
 * @des  配置类
 *      @EnableScheduling   开启对计划任务的支持
 */
@Configuration
@ComponentScan("com.leonard4")
@EnableScheduling
public class ScheduleTaskConfig {
}

2.3 运行 Main

每隔5秒输出一次,@Scheduled(cron = “0 14 16 ? * *”)指定时间点会输出一次

package com.leonard4;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Leonard.Z
 * @date 2020/9/26  16:08
 * @des 每隔五秒执行一次:16:13:58
 * 在指定时间16:14:00执行
 * 每隔五秒执行一次:16:14:03
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScheduleTaskConfig.class);

    }
}

4.条件注解@Conditional

1.点睛

@Conditional根据满足某一特定条件创建一个特定Bean,即根据特定条件来控制Bean的创建行为,利用这一特性进行一些自动配置。
【以不同操作系统为例】:
通过实现【Condition】接口,重写【matches】方法构造判读条件,若在Windows系统运行,输出‘dir’;若再Linux系统运行,输出‘ls’。

2.示例

1.判断条件定义

package com.leonard5;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:31
 * @des 判断条件定义-Windows
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("os.name").contains("Windows");
    }
}

package com.leonard5;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:35
 * @des Linux 系统 判断
 */
public class LinuxWindows implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("os.name").contains("Linux");
    }
}

2.不同系统下Bean类,实现一个公共接口

接口

package com.leonard5.i;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:37
 * @des 接口
 */
public interface ListService {
    public String showListcmd();
}

Windows下创建的Bean类

package com.leonard5.bean;

import com.leonard5.i.ListService;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:39
 * @des WindowsListService 下创建的Bean类
 */
public class WindowsListService implements ListService {

    @Override
    public String showListcmd() {
        return "dir";
    }
}

Linux下创建的Bean类

package com.leonard5.bean;

import com.leonard5.i.ListService;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:45
 * @des
 */
public class LinuxListService implements ListService {
    @Override
    public String showListcmd() {
        return "ls";
    }
}

3.配置类
通过@Conditional注解:
符合Windows条件则实例化windowsListService
符合Linux条件则实例化LinuxListService

package com.leonard5.config;

import com.leonard5.LinuxWindows;
import com.leonard5.WindowsCondition;
import com.leonard5.bean.LinuxListService;
import com.leonard5.bean.WindowsListService;
import com.leonard5.i.ListService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;


@Configuration
public class ConditionConfig {
    @Bean
    @Conditional(WindowsCondition.class)
    public ListService windowsListSerice(){
        return new WindowsListService();
    }
    @Bean
    @Conditional(LinuxWindows.class)
    public ListService linuxListService(){
        return new LinuxListService();
    }
}

4.运行【Windows系统下运行】
输出结果:
Windows 10系统下的命令为:dir

package com.leonard5;

import com.leonard5.config.ConditionConfig;
import com.leonard5.i.ListService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author Leonard.Z
 * @date 2020/9/28  10:48
 * @des
 */
public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
        ListService bean = context.getBean(ListService.class);
        System.out.println(context.getEnvironment().getProperty("os.name")+"系统下的命令为:"+bean.showListcmd());
        context.close();
    }
}

5.组合注解与元注解

1.【元注解】:实质上就是注解到别的注解上的注解,被注解的注解就是【组合注解】,组合注解具备元注解的功能;
2.【例如】@Configuration和@ComponentScan就是一个【组合注解】,表明这个类也是一个Bean;
3.使用【@WiselyConfiguration】注解替换@Configuration和@ComponentScan就是一个【组合注解】

FreeSWITCH编译安装详细文档 本文档详细介绍了在Ubuntu 22.04系统上从源码编译安装FreeSWITCH的完整流程。主要内容包括:1)系统环境准备和依赖库安装;2)关键依赖库spandsp和sofia-sip的编译安装;3)FreeSWITCH源码的特定版本(v1.6.0)编译配置,包括禁用SignalWire模块的配置方法;4)系统服务配置,包括创建专用用户、设置权限以及配置systemd服务文件。文档特别提供了版本控制说明,确保后期能切换到相同的版本环境,并附有详细的命令操作步骤和注意事项。 阅读详情

相关推荐

Anolis OS 23实战:5分钟搞定AI环境配置(含NVIDIA驱动一键安装)

本文详细介绍了如何在Anolis OS 23上快速配置AI开发环境,包括NVIDIA驱动的一键安装和TensorFlow、PyTorch等AI框架的部署。通过智能硬件适配引擎和优化后的二进制包,用户可在5分钟内完成传统需要数小时的配置工作,显著提升AI项目开发效率。

weixin_30335575的博客 538

在多线程异步方法中 Spring Security 框架的 SecurityContext 获取认证信息错误原因及解决方案

解决SecurityContext获取认证信息错误

lhq199667的博客 1976

Windows: 深入剖析pip install SSLError与SSL模块缺失的根源及系统级修复

本文深入分析Windows系统下pip install SSLError与SSL模块缺失的根本原因,提供系统级修复方案。从Python安装包缺失SSL支持、OpenSSL库冲突到环境变量配置问题,详细讲解四大成因及对应的解决方案,包括重新安装Python、手动修复OpenSSL依赖等实用技巧,帮助开发者彻底解决HTTPS连接问题。

weixin_28595749的博客 459

解决SpringSecurity上下文自动设置

问题: 我们用用异步线程的时候不能把SpringSecurity当前用户信息context带到子线程。 为了方便,我们需要进行信息透传 解决方法 需要加个参数 -Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL 或者增加代码块 static { System.setProperty(SYSTEM_PROPERTY, MODE_INHERITABLETHREADLOCAL); } .

吴国凯的博客 2103

基于角谱传播的MATLAB仿真:从相位恢复看自由空间光传播

本文详细介绍了基于角谱传播理论的MATLAB仿真方法,用于模拟自由空间光传播过程。通过傅里叶光学原理,将光场分解为频谱并应用传播相位滤波器,实现了从纯相位物体到可观测衍射图样的仿真。文章结合具体代码,演示了如何利用角谱法进行相位恢复,为计算成像和生物医学检测等领域的研究提供了实用的仿真工具和思路。

weixin_29055699的博客 283

Ansys Zemax与Speos协同设计:HUD系统从光学优化到驾驶视觉验证全流程解析

本文详细解析了如何利用Ansys Zemax与Speos协同工作流,完成HUD系统从光学内核优化到驾驶视觉验证的全流程。通过Zemax进行精密光学设计与像差校正,再通过Speos进行HOA定量分析和虚拟驾驶舱仿真,实现了数据无损流转与验证闭环,有效解决了光学性能与视觉感知脱节的核心问题,显著提升HUD设计效率与可靠性。

git9versioner的博客 530

SecurityContextHolder 管理安全上下文的核心组件详解

摘要: SecurityContextHolder是Spring Security的核心组件,负责通过ThreadLocal存储当前线程的SecurityContext(包含用户认证信息如身份、权限等),实现线程隔离和安全信息共享。开发者可通过其API获取/设置上下文,支持控制器、服务层及异步任务(需配置传递机制)。默认自动清理上下文,避免线程复用风险。作为连接认证与业务逻辑的桥梁,它实现了无侵入式安全访问,是权限控制的关键基础。使用时需注意异步场景的上下文传递和线程安全问题。

魏波 1736

电子电气架构 --- 整车电源管理

保证启动能力:防止因电池电量耗尽而导致的车辆无法启动,这对于确保车辆在任何时候都能可靠运行至关重要。 延长电池寿命:通过避免电池深度放电,有助于延长其使用寿命,减少更换电池的需求和成本。 提升用户体验:虽然负载被关闭可能会暂时影响舒适度,但通过在必要时自动采取行动,可以减少驾驶员的焦虑和不确定性,提高整体的用户满意度。

Soly_kun的博客 1088

Android学习系列(37)--App调试内存泄露之Context篇(下)

接着《Android学习系列(36)--App调试内存泄露之Context篇(上)》继续分析。 5. AsyncTask对象 我N年前去盛大面过一次试,当时面试官极力推荐我使用AsyncTask等系统自带类去做事情,当然无可厚非。 但是AsyncTask确实需要额外注意一下。它的泄露原理和前面Handler,Thread泄露的原理差不多,它的生命周期和Act...

dianan1505的博客 213

52、切换线性动态系统:原理、挑战与高斯和滤波解决方案

本文介绍了切换线性动态系统(SLDS)的基本原理及其在复杂时间序列建模中的应用。SLDS结合了隐马尔可夫模型的离散状态切换与线性动态系统的连续状态演化,适用于系统动态发生跳跃的场景,如化工过程监测和金融市场分析。由于精确推理在计算上不可行,文章重点阐述了高斯和滤波这一近似方法,通过有限高斯混合来逼近后验分布,并详细描述了其递归更新、权重计算与组件合并流程。同时讨论了性能评估、优化策略及常见问题的解决方案,并展望了SLDS与深度学习、在线学习和多模态融合的未来发展方向。

algae的博客 161

抖音移动端Web用户主页视频列表爬虫实战:逆向加密参数与高频采集方案

App端Hook/抓包:需要安卓逆向、Xposed或Frida,门槛高且容易被风控。官方开放API:限制极多,几乎不开放用户级视频列表。PC端Web:页面加载方式繁杂,且大量依赖懒加载与内部状态。移动端Web(:接口相对稳定,加密逻辑集中,且适合使用Requests/HTTPSession模拟,无需渲染引擎。本文聚焦于移动端Web下的用户主页视频列表爬取,采用Python 3.11 + httpx + PyExecJS + 正则/JSON解析的组合,破解X-Bogus签名和_signature。

2201_76125261的博客 868

Spring Boot实战(3) Spring高级话题

1. Spring Aware Spring的依赖注入的最大亮点就是你所有的Bean对Spring容器的存在是没有意识的。即你可以将你的容器替换成别的容器。 实际项目中,不可避免地会用到Spring容器本身的功能资源,这时的Bean必须意识到Spring容器的存在,才能调用Spring所提供的资源,这就是所谓的Spring Aware。 Spring提供的Aware接口如下: ...

debang2014010的专栏 211

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

【SpringBoot】一文了解SpringBoot配置高级

本文介绍的是SpringBoot配置高级部分,课程是跟着黑马走的,所以会有一些借鉴,当然也是笔记,还会参考一些大佬的分享;这里的SpringBoot配置高级,并不是SpringBoot所有的高级配置;SpringBoot体系(或者说Spring)是十分庞大的,笔者也自知不能穷尽,故而只能把所学的东西拿来记一记,练一练。文章内容如若有误,还请大家批评指正。

未来可以改变 2962

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

SpringBoot 高级知识

SpringBoot 高级知识 文章目录SpringBoot 高级知识视图技术。部署 SpringBoot 应用。Testing 单元测试。Rest 风格。MongoDB。Redis 。Elasticsearch。Cache 。Spring Session。SpringBoot 和 zookeeper 。监控 SpringBoot 应用。 视图技术。 部署 SpringBoot 应用。 Testi...

RobertChao的博客 5649

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

计算机毕业设计springboot基于用户的协同过滤算法的话题推荐 SpringBoot框架下融合用户行为分析的个性化话题推送平台 基于用户相似度计算的社交话题智能匹配与推荐引擎

摘要:本文介绍了一个基于SpringBoot框架和用户协同过滤算法的话题推荐系统。系统采用B/S架构,结合Vue.js前端和MySQL数据库,实现了话题浏览、搜索、收藏、评论等用户功能,以及内容管理、数据分析等管理功能。核心算法通过构建用户-话题评分矩阵,运用余弦相似度/KNN计算用户相似度,解决信息过载问题。系统具有响应高效(3秒内)、操作简便、存储量大等特点,并通过技术、经济、操作三方面可行性验证。开发采用Java+SpringBoot+MySQL技术栈,包含完整的系统设计、数据库E-R图和功能模块说明

毕设源码_廖学姐 1171

Springboot整合ElasticSearch第三章高级查询

1.基本查询 先看看基本玩法 @Test public void testQuery(){ // 词条查询 MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "小米"); // 执行查询 Iterable<Item> items = this.itemRepository...

RememberQian的博客 982

Sprin源码-高级话题整体梳理

一、大纲 1.1 高级话题 1.2 二、Springboot 开发测试 三、数据缓存

u012432276的博客 142

SpringBoot高级教程

SpringBoot的高级教程 一、SpringBoot缓存 缓存的场景 临时性数据存储【校验码】 避免频繁因为相同的内容查询数据库【查询的信息】 1、JSR107缓存规范 用的比较少 Java Caching定义了5个核心接口 CachingProvider 定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可以在运行期间访问多个CachingProvider CacheManager 定义了创建、配置、获取、管理和控制多个唯一命名的Cache,这些Cache存在于C

北眼的博客 1756

【2026计算机毕业设计】基于Springboot的话题推荐系统

MySQL是一个开源和多线程的关系管理数据库系统,MySQL是开放源代码的数据库,具有跨平台性,虽然功能未必强大,导致很多人都了解这个数据库的基本应用,在数据库中,总共建立了10几个表,这里面每个表都是相对应的,都各自有各自的联系,数据库意义重大,如果没有数据库的链接,就没办法运行程序,这显然可以看见数据库与程序的重要性,是紧密相连接的[9]。因为Java 技术具有卓越的通用性、高效性、健壮的安全性和平台移植性的特点,而且Java是开源的,拥有全世界最大的开发者专业社群,所以Java的发展迅速。

xiaoshuaibishe的博客 1091

SpringBoot高级

springboot高级 本文分别从缓存、消息、检索、任务、安全、分布式、热部署和监控管理方面,对spring boot高级部分做了简单总结,内容不深但覆盖全。 (一) Spring Boot与缓存 一、 JSR107 Java Caching定义了5个核心接口 CachingProvider 定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可 以在运行期访问多个CachingProvider。 CacheManager 定义了创建、配置、获取、管理和控制多个唯一命名的Ca

weixin_43102784的博客 765

SpringBoot高级用法

1,IDEA中Lombok作用

qq_60509834的博客 3488

第四部分:SpringBoot高级功能

1.背景介绍 1. 背景介绍 Spring Boot是一个用于构建Spring应用程序的框架,它提供了一种简化的配置和开发过程,使得开发人员可以更快地构建高质量的应用程序。在这篇文章中,我们将深入探讨Spring Boot的高级功能,揭示它们如何帮助开发人员构建更高效、可靠和可扩展的应用程序。 2. 核心概念与联系 在深入探讨Spring Boot高级功能之前,我们需要了解一些核心概念和它...

AI天才研究院 1080

springboot高级篇

SpringBoot高级篇 一、SpringBoot基础篇 1.SpringBoot初探 ​ SpringBoot的初衷简化配置 2.SpringBoot项目的构建方式 2.1 通过官网自动生成 https://start.spring.io/ 快速生成 2.2 IDE 在线模板生成 本质上和上面是一样的,只是简化了我们的操作 2.3 IDE通过maven项目构建 1.创建一个独立的web项目 2.引入对应依赖 <parent> <groupId>org.spri

weixin_43914685的博客 5918

SpringBoot高级特性

高级特性 Profile 为了方便多环境开发,springboot简化了profile功能 application-prod.yaml 开发环境配置 server: port: 5001 application-test.yaml 测试环境配置 server: port: 8080 application.yaml 使用profile spring: profiles: active: test或者prod 第二种激活方式, 命令行激活 java -jar xxxx.jar

qq_58855682的博客 737

Springboot高级

springboot高级

软件Java开发工程师 357

【SpringBoot】Spring Boot 中高级特性详解

在现代应用中,处理大量并发请求和长时间运行的任务时,异步处理是一种有效的方式。Spring Boot 通过注解和@Async注解实现了异步方法的调用,从而避免了阻塞主线程,提高了系统的响应速度和吞吐量。可以通过实现@Service@Override// 根据用户名查找用户信息并返回可以通过实现@Component@Override// 自定义健康检查逻辑} else {// 执行健康检查逻辑可以通过文件自定义 Logback 的日志配置:

Easonmax的博客 1554
上一篇: JavaSE基础及案例(二)多线程(下)与简单工厂模式的了解
下一篇: 2021-07-09 Demo 输入一个数字顺时针打印出矩阵
一朝游
博客等级 码龄8年 0粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值