Springboot web工程中多数据源配置

SpringBoot实现mysql多数据源配置(Springboot+Mybatis) 使用postman进行接口测试,在这里只展示insertUser的测试界面postman调用一个数据源的insertUser接口第一个数据库查询结果postman调用一个数据源的insertUser接口第二个数据库查询结果。 阅读详情

在一个web工程中,经常需要访问多个不同的数据源,因此需要进行多数据源配置。以Springboot构建的web工程为例,进行了对数据源的配置。

首先在application-prod.properties文件中定义访问不同数据源的url和账户密码,如下(以两个数据源为例,sqlserver有些差别):

#要连接的数据源1 db1
spring.datasource.primary.url=jdbc\:mysql\://localhost\:3306/db1?useUnicode\=true&characterEncoding\=utf-8
spring.datasource.primary.username=root
spring.datasource.primary.password=******
spring.datasource.primary.driveClassName=com.mysql.jdbc.Driver



#要连接的数据源2 db2
spring.datasource.secondary.url=jdbc\:mysql\://localhost\:3306/db2?useUnicode\=true&characterEncoding\=utf-8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=******
spring.datasource.secondary.driveClassName=com.mysql.jdbc.Driver

然后,分别对两个数据源进行配置,使用Druid做数据库连接池,并实现监控功能,因此需要引入Druid,并对其进行配置,配置成功后可以实现对整个工程访问数据库的监控。首先要做的当然是在pom文件中引入druid相关的jar,也就是添加druid依赖,应该是在springboot2.0之后将druid添加了进来,依赖如下:

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.9</version>
    </dependency>

由于目前spring Boot中默认支持的连接池有dbcp,dbcp2,tomcat,hikari三种连接池,因此需要进行配置信息定制,因此在文件application-prod.properties文件中添加对druid的相关配置,如下:


spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
spring.mvc.static-path-pattern=/static/**

配置信息搞好以后,需要Config文件将properties文件中设置的参数和监控相关的参数在工程启动的时候应用起来,配置文件如下:

public class DruidDBConfiguration {

	@Value("${spring.datasource.initialSize}")
	private int initialSize;
	
	@Value("${spring.datasource.minIdle}")
	private int minIdle;
	
	@Value("${spring.datasource.maxActive}")
	private int maxActive;
	
	@Value("${spring.datasource.maxWait}")
	private int maxWait;
	
	@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
	private int timeBetweenEvictionRunsMillis;
	
	@Value("${spring.datasource.minEvictableIdleTimeMillis}")
	private int minEvictableIdleTimeMillis;
	
	@Value("${spring.datasource.validationQuery}")
	private String validationQuery;
	
	@Value("${spring.datasource.testWhileIdle}")
	private boolean testWhileIdle;
	
	@Value("${spring.datasource.testOnBorrow}")
	private boolean testOnBorrow;
	
	@Value("${spring.datasource.testOnReturn}")
	private boolean testOnReturn;
	
	@Value("${spring.datasource.poolPreparedStatements}")
	private boolean poolPreparedStatements;
	
	@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
	private int maxPoolPreparedStatementPerConnectionSize;
	
	public int getInitialSize() {
		return initialSize;
	}

	public void setInitialSize(int initialSize) {
		this.initialSize = initialSize;
	}

	public int getMinIdle() {
		return minIdle;
	}

	public void setMinIdle(int minIdle) {
		this.minIdle = minIdle;
	}

	public int getMaxActive() {
		return maxActive;
	}

	public void setMaxActive(int maxActive) {
		this.maxActive = maxActive;
	}

	public int getMaxWait() {
		return maxWait;
	}

	public void setMaxWait(int maxWait) {
		this.maxWait = maxWait;
	}

	public int getTimeBetweenEvictionRunsMillis() {
		return timeBetweenEvictionRunsMillis;
	}

	public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
		this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
	}

	public int getMinEvictableIdleTimeMillis() {
		return minEvictableIdleTimeMillis;
	}

	public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
		this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
	}

	public String getValidationQuery() {
		return validationQuery;
	}

	public void setValidationQuery(String validationQuery) {
		this.validationQuery = validationQuery;
	}

	public boolean isTestWhileIdle() {
		return testWhileIdle;
	}

	public void setTestWhileIdle(boolean testWhileIdle) {
		this.testWhileIdle = testWhileIdle;
	}

	public boolean isTestOnBorrow() {
		return testOnBorrow;
	}

	public void setTestOnBorrow(boolean testOnBorrow) {
		this.testOnBorrow = testOnBorrow;
	}

	public boolean isTestOnReturn() {
		return testOnReturn;
	}

	public void setTestOnReturn(boolean testOnReturn) {
		this.testOnReturn = testOnReturn;
	}

	public boolean isPoolPreparedStatements() {
		return poolPreparedStatements;
	}

	public void setPoolPreparedStatements(boolean poolPreparedStatements) {
		this.poolPreparedStatements = poolPreparedStatements;
	}

	public int getMaxPoolPreparedStatementPerConnectionSize() {
		return maxPoolPreparedStatementPerConnectionSize;
	}

	public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
		this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
	}

	public String getFilters() {
		return filters;
	}

	public void setFilters(String filters) {
		this.filters = filters;
	}

	public String getConnectionProperties() {
		return connectionProperties;
	}

	public void setConnectionProperties(String connectionProperties) {
		this.connectionProperties = connectionProperties;
	}

	@Value("${spring.datasource.filters}")
	private String filters;
	
	@Value("{spring.datasource.connectionProperties}")
	private String connectionProperties;
	
	@Bean  //声明其为Bean实例
	@Primary //在同样的DataSource中,首先使用被标注的DataSource
	public DataSource dataSource(){
		DruidDataSource datasource = new DruidDataSource();
		
		//configuration
		datasource.setInitialSize(initialSize);
		datasource.setMinIdle(minIdle);
		datasource.setMaxActive(maxActive);
		datasource.setMaxWait(maxWait);
		datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		datasource.setValidationQuery(validationQuery);
		datasource.setTestWhileIdle(testWhileIdle);
		datasource.setTestOnBorrow(testOnBorrow);
		datasource.setTestOnReturn(testOnReturn);
		datasource.setPoolPreparedStatements(poolPreparedStatements);
		datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
		
		
		try {
			datasource.setFilters(filters);
		} catch (SQLException e) {
			System.out.println("druid configuration initialization filter"+e);
			e.printStackTrace();
		}
		
		datasource.setConnectionProperties(connectionProperties);
		
		return datasource;
		
	}
	
	
	
	@Bean
	public ServletRegistrationBean DruidStatViewServlet2(){
		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
		
		servletRegistrationBean.addInitParameter("allow", "127.0.0.1");//ip地址需要修改!!!必须要修改
		servletRegistrationBean.addInitParameter("deny", "10.100.8.38");
		servletRegistrationBean.addInitParameter("loginUsername", "administrator");
		servletRegistrationBean.addInitParameter("loginPassword", "123456");
		
		//能否重置数据
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		
		return servletRegistrationBean;
	}
	
	
	@Bean
	public FilterRegistrationBean druidStatFilter2(){
		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
		
		filterRegistrationBean.addUrlPatterns("/*");
		
		//添加不需要忽略的格式信息
		filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
		return filterRegistrationBean;
	}
}

这样之后,druid可以作为数据库连接池使用,并且能够提供监控功能,接下来需要配置我们添加的两个数据源。两个配置类分别为PrimaryDataSourceConfig和secondaryDataSourceConfig

@Configuration
@MapperScan(basePackages = {"**.**.******.Dao.********Dao"}, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {
	
	@Bean(name = "primaryDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.primary")
	public DataSource primaryDataSource(){
		
		return DruidDataSourceBuilder.create().build();
	}
	
	
    // 创建该数据源的事务管理
    @Primary
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(primaryDataSource());
    }
    
    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory backSqlSessionFactory(@Qualifier("primaryDataSource") DataSource backDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(backDataSource);
/*        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:"));*/

        sessionFactory.setTypeAliasesPackage("**.**.******.Dao.**************Dao");
        
        return sessionFactory.getObject();
    }

}
@Configuration
@MapperScan(basePackages = {"**.**.******.Dao.********Dao"}, sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class secondaryDataSourceConfig {

	@Bean(name = "secondaryDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.secondary")
	public DataSource secondaryDataSource(){
		
		return DruidDataSourceBuilder.create().build();
	}
	
	@Primary
    // 创建该数据源的事务管理
    @Bean(name = "secondaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(secondaryDataSource());
    }
    
	
    @Bean(name = "secondarySqlSessionFactory")
    public SqlSessionFactory backSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource backDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(backDataSource);
/*        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:"));*/

        sessionFactory.setTypeAliasesPackage("**.**.******.******************Dao");
        
        return sessionFactory.getObject();
    }
}

在两个配置类中,将对不同的数据源的Dao层的操作放在不同的package下边,MapperScan指定不同的数据源对应扫描不同的Dao层接口。这样就可以实现同一个工程中对不同的数据源的访问了。当做笔记,之后用到可当做参考。

 

SpringBoo Mybatis Druid配置多数据源 SpringBoo Mybatis Druid配置多数据源 前言:当单个数据库无法满足大量读写操作需求的时候,就需要用到多个数据库实现读写分离了。那么,这个时候,就需要去配置多数据源了。那么具体如何配置呢?本就将给出基本的配置示例… 一 创建两个数据库用于测试 我这里分别创建了 datasourceone 和 datasourcetwo 两个数据库,并分别创建了t_user 和 t_student... 阅读详情

相关推荐

springboot+ibatis 多数据源配置

废话少说吧,直接进入主题,首先新建一个maven项目,pom.xml引入基本的jar包这个是boot基本版本包,因为我用的打包方式是war所以去除掉了boot内置的tomcat,但是为了方便测试又引入了内置tomcat,只要添加&lt;scope&gt;provided&lt;/scope&gt;在打包时就不会影响了。&lt;parent&gt; &lt;groupId&gt;org.sp...

crqnyf的博客 9228

SpringBoot项目配置多数据源

1. 修改application.yml 注意 连接多个数据库时,url要更改为jdbc-url,否则会报错。 多数据源的配置中需要指定具体的名称来区分不同的数据库(上述配置中的dev和local,名称可以根据具体需求自定义) mybatis配置别名不起作用,因此注释掉了。 #mybatis: # type-aliases-package: usts.eie.sbmp.pojo spring: datasource: dev: username: root pa

拧发条鸟的博客 4222

狂神IT学习笔记全集:Java与前端到分布式服务

Java语言是一种面向对象、跨平台的编程语言。它继承了C++语言的特性,同时舍弃了指针等不安全特性。Java语言的“一次编写,到处运行”特性,使其成为构建企业级应用的首选。MyBatis允许自定义插件来增强功能,这些插件可以拦截接口方法调用或映射文件中的SQL语句执行。自定义插件需要实现接口,并在配置文件中进行注册。})@Override// 在调用前后实现逻辑@Override// 设置插件属性在自定义插件的实现中,我们使用注解定义了要拦截的方法和参数类型。

weixin_35987118的博客 1110

SpringBoot多数据源

多套数据源: ​ 定义:在项目中针对一个数据库都为其建立一套独立的数据处理逻辑,包括数据源(DataSource),会话工厂(SqlSessionFactory),连接,DAO操作。 一、搭建springboot工程 ​ 项目工程结构如下所示,主要从实体类和Mapper层开始进行划分,实际工作可从Service层进行划分。 ├─config ---------------------------------- // 数据源配置 ├─controller ------------------------

Kesling515 2万+

ESP32 CAM安装配置 第四部份:通过使用ESPHome的方式ESP32 Cam加到HomeAssistant

这些包括 aec_value, aec2, ae_level, agc_gain, gain_ctrl, bpc, wpc, raw_gma, lenc, hmirror, dcw, colorbar 等。这些参数的可能值和具体效果会根据你的摄像头硬件和 ESPHome 的版本有所不同。在 ESPHome 中配置 ESP32 Cam 时,每个参数的可能值取决于具体的功能和支持范围。值的范围是 0 到 63,其中 0 是最差质量,63 是最佳质量。horizontal: 水平校正的强度,通常是一个数字值。

weixin_42895252的博客 3369

matlab中的神经网络怎么用,matlab怎么搭建神经网络

图中 yi表示神经元i的输出,函数f称为激活函数 ( Activation Function )或转移函数 ( Transfer Function ) ,net称为净激活(net activation)。图中x1~xn是从其他神经元传来的输入信号,wij表示表示从神经元j到神经元i的连接权值,θ表示一个阈值 ( threshold ),或称为偏置( bias )。对于P,x1是行向量,x2是行向量。双极S形函数与S形函数主要区别在于函数的值域,双极S形函数值域是(-1,1),而S形函数值域是(0,1)。

wenangou的博客 6370

springboot 多数据源配置的几种方式

springboot多数据源配置的几种方式

A_awen的博客 6608

医疗器械软件测试输出内容(1)

*单元测试(Unit Testing):**单元测试是软件测试的最底层,用于验证软件中最小的可测试单元——函数、方法或模块。系统测试是在集成测试之后进行的,它对整个系统进行测试,验证系统在不同部分集成在一起后是否满足需求和规格。: 集成测试是在单元测试之后进行的,它关注不同单元之间的交互和集成。对于不同安全级别的软件(IEC 62304 A类、B类、C类),在体系上要求输出的文件内容有所区别。**说明:**将集成测试和软件系统测试合并为一项单一的计划和一组活动是可接收的。

ct745363083的博客 1870

SpringBoot配置多数据源(application.yml)

简单三步解决springboot配置多数据源

u010786200的博客 1868

【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

一只爱做笔记的码农 3398

S7-1200 PN与G120变频器控制起停及调速PROFINET实现详解

S7-1200 PLC与G120变频器通过PROFINET通信可实现高效、实时的电机控制。2. 《S7-1200与G120 CU250S-2PN的PROFINET通讯指南》- 控制器:S7-1200 PLC (如1214C DC/DC/DC)- 变频器:G120 CU250S-2PN (带PROFINET接口)- 输出区(PZD1-2):控制字(16位)、速度设定值(16位)- 输入区(PZD1-2):状态字(16位)、实际速度值(16位)- P922=1:选择报文类型为"标准报文1 (PZD2/2)"

电工 1882

springboot项目多数据源配置

springboot项目多数据源配置

captain_zhangYC的博客 3330

5.3-集群电源模式解析

DSU-120 DynamIQ™集群支持9种电源模式,包括正常运行(ON)、完全断电(OFF)、三种数据保持模式(FUNC_RET、FULL_RET、MEM_RET)、两种调试模拟模式(OFF_EMU、MEM_RET_EMU),以及系统恢复模式(WARM_RST、DBG_RECOV)。这些模式通过智能管理电源状态,在保持数据完整性的同时实现功耗优化,并为系统调试和故障恢复提供支持。不同模式在RAM保持、逻辑断电和调试能力方面各有侧重,满足从正常运行到深度调试等不同场景需求。

baron-周贺贺-代码改变世界ctw 119

mybatis依赖_最简单的SpringBoot整合MyBatis教程

前面两篇文章和读者聊了Spring Boot中最简单的数据持久化方案JdbcTemplate,JdbcTemplate虽然简单,但是用的并不多,因为它没有MyBatis方便,在Spring+SpringMVC中整合MyBatis步骤还是有点复杂的,要配置多个Bean,Spring Boot中对此做了进一步的简化,使MyBatis基本上可以做到开箱即用,本文就来看看在Spring Boot...

weixin_39521808的博客 1147

加密算法:深度解析Ed25519原理

在 Solana 开发过程中,我一直对 Ed25519 加密算法 如何生成公钥、签名以及验证签名的机制感到困惑。为了弄清这一点,我查阅了大量相关资料,终于对其流程有了更清晰的理解。在此记录实现过程,方便日后查阅。

盹猫的博客 1万+

深度学习工具包 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 Spring介绍 1.1、SpringBoot简介 在您第1次接触和学习Spring框架的时候,是否因为其繁杂的配置而退却了?在你第n次使用Spring框架的时候,是否觉得一堆反复黏贴的配置有一些厌烦?那么您就不妨来试试使用Spring Boot来让你更易上手,更简单快捷地构建Spring应用! Spring Boot让我们的Spring应用变的更轻量化。比如:你可以仅...

java技术专家全栈成长之路 412

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

spring-boot和mybatis的整合

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34049948的博客 124

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

SpringBoot实现多数据源配置

SpringBoot实现多数据源配置

北执南念的博客 3325

Spring Boot多数据源配置之JdbcTemplate

多数据源配置也算是一个常见的开发需求,Spring和SpringBoot中,对此都有相应的解决方案,不过一般来说,如果有多数据源的需求,我还是建议首选分布式数据库中间件MyCat去解决相关问题,之前有小伙伴在我的知识星球上提问,他的数据根据条件的不同,可能保存在四十多个不同的数据库中,怎么办?这种场景下使用多数据源其实就有些费事了,我给的建议是使用MyCat,然后分表策略使用sharding-by...

江南一点雨的专栏 1万+

springboot整合druid及多数据源配置

本篇主要分两部分 ①springboot整合druid的代码配置,以及druid的监控页面演示;②对实际场景中多数据源的配置使用进行讲解。

橙子的随笔集 7003

springboot+mybatis实现多数据源配置

springboot+mybatis实现多数据源配置

ldcaws的专栏 9763

Springboot 2.x + JPA 配置多数据源实战

在进行web开发的时候,有时候会出现需要调用另一个数据库的需求。这篇文章将教会你如何达到此目的,并提供了一键即用的完整代码给各位尝试。

学习即修行 6万+

SpringBoot集成MyBatis配置多数据源详细教程

一、工程创建 申明一点本案例使用的springboot版本是1.5.6.RELEASE。首先需要创建springBoot项目,添加springBoot框架对MyBatis支持的相关依赖Jar:分别添加MyBatis、MySQL以及Web依赖以及Druid依赖,这里添加Druid依赖必须是Spring boot支持的Druid,不能使用传统的Druid。完整的依赖jar如下: <depe...

奋斗的IT青年 1437

Spring Boot多数据源配置之Mybatis

Spring Boot多数据源配置之Mybatis前言创建工程多数据源配置Mybatis配置Mapper 前言   关于多数据源的配置,前面介绍过JdbcTemplate多数据源配置,那个比较简单,本文来说说MyBatis多数据源的配置。其实关于多数据源,复杂的就直接上分布式数据库中间件,简单的再考虑多数据源。这是项目中的建议,技术上的话,当然还是各种技术都要掌握的。 创建工程   还是跟前文一样...

JustinNeil的博客 318

Spring Boot整合Jpa多数据源

Spring Boot整合Jpa多数据源 本文是Spring Boot整合数据持久化方案的最后一篇,主要和大伙来聊聊Spring Boot整合Jpa多数据源问题。在Spring Boot整合JbdcTemplate多数据源、Spring Boot整合MyBatis多数据源以及Spring Boot整合Jpa多数据源这三个知识点中,整合Jpa多数据源算是最复杂的一种,也是很多人在配置时最容易出错的一...

liuzuoping的博客 2402
上一篇: 对List中的对象按照特定属性进行排序
下一篇: Springboot+Shiro实现权限控制
Rolandcoder
博客等级 码龄10年 19粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值