自定义数据库连接池和Druid介绍

springboot使用yml方式配置Druid连接池 官方:数据库连接池(Connection pooling)是程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对池中的连接进行申请,使用,释放。 使用数据库连接池,省略(复用)了创建连接和销毁连接的过程(TCP连接建立时的三次握手和销毁时的四次握手),从而在性能上得到了提高。 使用了数据库连接池的机制: (1) 程序初始化时创建连接池 (2) 使用时向连接池申请可用连接 (3) 使用完毕,将连接返还给连接池 (4) 程序退出时,断开所有连接,并释放资源 什么是Druid连接池 Dru 阅读详情

常见的数据库连接池有c3p0、dbcp、druid(阿里巴巴开源,结合前面两者优点,加入日志监控,目前最好用的数据库连接池)

自定义数据库连接池

ConnectionPool.java

package test.testCoonPool;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.Properties;

public class ConnectionPool {
    private static ConnectionPool pool;

    private static String driverClass;
    private static String url;
    private static String username;
    private static String password;
    //初始连接数
    private static int initCount = 5;
    //最小连接数
    private static int minCount = 5;
    //最大连接数
    private static int maxCount;
    //当前连接数
    private static int currentCount;
    //使用集合存储连接
    LinkedList<Connection> conns = new LinkedList<>();
    //成员属性初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(ConnectionPool.class.getClassLoader().getResourceAsStream("db.properties"));
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            driverClass = properties.getProperty("jdbc.driverClass");
            try{
                initCount = new Integer(properties.getProperty("jdbc.initCount"));
            }catch (NumberFormatException e){
                System.out.println("initCount使用默认值");
            }
            try{
                minCount = new Integer(properties.getProperty("jdbc.minCount"));
            }catch (NumberFormatException e){
                System.out.println("minCount使用默认值");
            }
            try{
                maxCount = new Integer(properties.getProperty("jdbc.maxCount"));
            }catch (NumberFormatException e){
                System.out.println("maxCount使用默认值");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ConnectionPool(){}
    public static ConnectionPool getPool(){
        if(pool==null){
            pool = new ConnectionPool();
        }
        return pool;
    }

    /**
     * 初始化数据库连接池
     */
    private void init(){
        for (int i = 0; i <initCount ; i++) {
           boolean flag = conns.add(createConn());
           if(flag){
               currentCount++;
           }
        }
        System.out.println("数据库连接池初始化完成");
        getCurrentCount();
    }

    private Connection createConn(){
        try{
            Class.forName(driverClass);
            return DriverManager.getConnection(url,username,password);
        }catch (Exception e){
            throw new RuntimeException("数据库连接创建失败,"+e.getMessage());
        }
    }

    /**
     * 从池中获取一个可用连接
     */
    public Connection getConn(){
        if(conns.size()>0){
            return conns.removeFirst();
        }else if(currentCount <maxCount){
            autoAdd();
            //递归调用返回连接
            return getConn();
        }else {
            //如果池中连接数已经达到上限,就不能扩充连接数了,就等一会(等有空闲连接)再获取
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getConn();
        }
    }

    /**
     * 数据库连接池连接数量自增长2 ,池中没有空闲连接时调用
     */
    private void autoAdd(){
        if(currentCount == maxCount){
            throw new RuntimeException("数据库连接池连接数量已经达到最大值!");
        }
        for (int i = 0; i <2 ; i++) {
            if(currentCount == maxCount){
                break;
            }
            conns.add(createConn());
            currentCount++;
        }
    }

    public int getCurrentCount(){
        System.out.println("当前数据库连接池数量:"+currentCount);
        return currentCount;
    }

    /**
     * 连接池自动缩减
     */
    private synchronized void reduce(){
        //当连接数量大于最小连接数量,并且池中有空闲连接
        if(currentCount > minCount && conns.size()>0){
            try{
                //从池中获取连接并关闭
                Connection con = conns.removeFirst();
                con.close();
                con = null;
                currentCount--;
            }catch (SQLException e){

            }
        }
    }

    public void returnCon(Connection conn){
        conns.add(conn);
        reduce();
    }

    public static void main(String[] args) {
        ConnectionPool.getPool().init();
    }
}

配置文件db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=xxx
jdbc.password=xxxxxx
jdbc.initCount=8
jdbc.minCount=8
jdbc.maxCount=20

自定义数据库连接池的使用
JDBCTool.java

package test.testCoonPool;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCTool {

    /**
     * 从数据库连接池中获取连接
     * @return
     */
    public static Connection getConn(){
        return ConnectionPool.getPool().getConn();
    }

    public static void closeAll(Statement st, ResultSet rs,Connection conn){
        try {
            if(st!=null)st.close();
            if(rs!=null)rs.close();
            if(conn!=null)ConnectionPool.getPool().returnCon(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

druid的使用

  • maven项目引入依赖
        <!-- 阿里巴巴druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.18</version>
        </dependency>

介绍一个概念,数据源对象——jva.sql.DataSource接口对象,表示数据源对象,可以直接理解为数据库连接池,所有的连接池都会有一个数据源实现这个接口。

Druid实现这个数据源的类是:DruidDataSource

druid.properties

jdbcUrl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
username=xxx
password=xxxxxx
initialSize=5
maxActive=15
minIdle=5
maxWait=3000

JDBCTool2

package test.testCoonPool;

import com.alibaba.druid.pool.DruidDataSource;
import javax.sql.DataSource;



import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCTool2 {

    private static DataSource dataSource;
    static {
        //需要加载配置
        try {
            Properties properties = new Properties();
            properties.load(JDBCTool2.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = new DruidDataSource();
            DruidDataSource druidDataSource = (DruidDataSource)dataSource;
            druidDataSource.setUrl(properties.getProperty("jdbcUrl"));
            druidDataSource.setUsername(properties.getProperty("username"));
            druidDataSource.setPassword(properties.getProperty("password"));
            druidDataSource.setInitialSize(new Integer(properties.getProperty("initialSize")));
            druidDataSource.setMaxActive(new Integer(properties.getProperty("maxActive")));
            druidDataSource.setMaxActive(new Integer(properties.getProperty("maxActive")));
            druidDataSource.setMinIdle(new Integer(properties.getProperty("minIdle")));
            druidDataSource.setMaxWait(new Long(properties.getProperty("maxWait")));
            dataSource = druidDataSource;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("创建druid连接池失败:"+e.getMessage());
        }
    }

    public  static Connection getCoon() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取连接失败:" + e.getMessage());
        }
    }

    public static void closeAll(Statement st, ResultSet rs, Connection conn){
        try {
            if(st!=null)st.close();
            if(rs!=null)rs.close();
            //使用Druid获取的连接直接关闭即可,它会自己还回池中
            if(conn!=null)conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

谈谈通过druidDataSource获取的Connection对象为什么用完后可以直接关闭,其实这是一个Connection代理对象,代理对象修改了原生对象的一些方法,特别是close方法。
代理Connection的close方法实际操作是:首先判断池中是否有过多的空闲连接,如果超过了最大空闲连接数,close会直接关闭,并且将这个连接从池中移除。如果池中的空闲连接数并不大于最大空闲连接数量,就不会关闭连接,而是标记为空闲状态。

Java数据库连接池原理及spring boot使用数据库连接池(HikariCP、Druid) - druid连接池核心包,不是spring boot官方提供的组件一般没有定义默认版本,所以需要指定版本 --> < dependency > < groupId > com.alibaba < artifactId > druid < version > 1.2.8 阅读详情

相关推荐

自定义druid连接池的工具类

1、druid连接池所需要的jar包和配置文件druid.properties,先配置好 2、自定义的druid的工具类 package cn.itcast.dataSource.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOE...

Shen_R的博客 462

用 Druid 连接数据库

1. 实体类 @Data @AllArgsConstructor @NoArgsConstructor public class TestTable { private Integer id; private String name; private Integer age; } 数据库表: 2. Maven依赖 <dependency> <groupId>commons-dbutils</grou

Janet的博客 1121

springboot-AOP实现多数据源动态切换(Druid连接池)

通过SpringAop实现多数据源的动态切换 并采用Druid连接池,可扩展继续增加数据库配置。

【详解】Druid连接池自定义数据库密码加解密的实现

在现代应用开发中,数据安全是至关重要的。特别是在处理数据库连接时,确保数据库密码的安全性是非常必要的。​​Druid​​ 是阿里巴巴开源的一个高性能的数据库连接池,它提供了丰富的配置选项和强大的监控功能。本文将介绍如何在 ​​Druid​​ 连接池中实现自定义的数据库密码加解密功能。创建一个自定义的Druid数据源类,重写密码设置方法,以便在设置密码时自动解密。// 存储的是加密后的密码@Bean// 解密密码@Bean// 解密密码。

牛肉胡辣汤 1764

手机也能跑大模型?QNN框架实战:从模型量化到Android部署全流程

本文详细介绍了如何利用QNN框架将大模型部署到Android手机端进行端侧推理。通过实战演示了从模型量化(如INT4/INT8混合精度)到Android应用集成的全流程,包括内存优化、性能调优及常见问题排查,帮助开发者实现大模型在资源受限设备上的高效本地运行。

joy55的博客 504

QGIS基于快鸟(QuickBird)影像统计小麦种植面积

​01数据情况 本次选用某地4月份快鸟(QuickBird)影像为例,使用QGIS演示提取小麦播种情况,并按照200米*200米分区计算种植面积的过程。 注:本文对应的操作视频作为今天第二篇推送同时发布,习惯看视频的朋友可以点击观看。 附数据压缩包: 链接:https://pan.baidu.com/s/1JVUS8uAOR61RxC1n9Or9_w 提取码:qgis 含快鸟影像QB_subset.tif和200*200米分区矢量图层200Mgrid.shp。 ...

QGISClass的博客 1983

Java自定义数据库连接池与Druid连接池

JDBC中提供了一个接口DataSource,所有的连接池都必须实现这个接口 自定义数据库连接池 创建一个连接池,继承DataSource接口并实现方法,其中只需要关注getConnection()一个方法即可,用于获取连接,然后再创建一个将连接 放回连接池的方法 package com.robot.utils; import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.Connection; import java.

她的坏机器人 871

高通Camera IFE时钟配置

高通Camera IFE时钟配置中的minHorizontalBlanking和minVerticalBlanking配置计算方法

一个懒癌的驱动工程师的随笔分享 6177

Day56 数据库连接池,Druid连接池

自己写的连接池类 FastConnectionPool//存储connection连接对象的资源容器(removeFirst)//get,set方法(没有list的get、set方法)//初始化listtry {//创建连接对象,并添加到连接池容器中i++) {init();if(!//回收connection对象,使用完了不用close()方法关闭,而是回收到list中继续使用,提高复用率测试类//创建数据库连接池//设置参数。

weixin_69595694的博客 1744

智能水下机器人设计: 基于MATLAB的水下机器人动力学建模和控制系统设计,包括水下环境感知、路径规划和任务执行等

智能水下机器人是指能够在水下自主完成各种任务的机器人,例如探测、勘察、救援等。它具有广阔的应用前景,可用于海洋环境监测、水下考古、海上作业等领域。基于MATLAB的水下机器人设计可以为科研人员和工程师提供强大的建模和仿真工具,帮助他们设计更智能、更高效的水下机器人。智能水下机器人是未来海洋科技发展的重要方向,它将为海洋科学研究、水下考古和海上作业等领域带来新的机遇。MATLAB是一种功能强大的数学和科学计算软件,它可以为智能水下机器人设计提供强大的工具和支持。

走向CTO的路上... 973

R语言] 使用循环在数据框中添加新列

假设我们有一个名为"df"的数据框,其中包含了一些数据。我们想要在该数据框中添加一个新列"new_column",并将其填充为每行的索引值。无论是使用循环还是矢量化操作,我们都可以根据具体需求修改代码来添加不同类型的新列,并进行各种计算。在R语言中,我们经常需要在数据框中添加新列来存储计算结果或其他信息。本文将介绍如何使用循环在数据框中添加新列,并提供相应的源代码示例。可以看到,数据框"df"中成功添加了一个名为"new_column"的新列,并且每行的值与其对应的索引值相同。

DevRevolt的博客 1374

spring boot 自定义druid数据源,如何注入配置

spring:druid:这种配置是没有问题,相信这种写法在网上一搜都有很多,我们可以验证下,druid的配置是生效的。如下,启动的时候打印druid相关配置信息:和我们配置文件中是一样,属性配置是成功注入生效的。使用druid的时候,我们可以自定义处理某些配置项,比如对数据库连接进行加密等操作。

程序猿的樊笼 4949

雷达工程师面试题目

详细描述项目背景、目标、你的具体职责和贡献,分析在项目实施过程中遇到的主要技术难题及解决方案,总结项目取得的成果和经验教训。

道亦无名 742

C3P0和Druid数据库连接池的简单使用;几种设计模式简介;简略介绍自定义数据库连接池注意点

数据库连接池 负责分配、管理和释放数据库连接; 它允许应用程序重复使用一个连接,而不是新建连接,提高了程序的效率; 由于新建数据库连接也是要耗费性能和时间的,当访问量十分巨大的时候,对程序性能的影响就极为显著,为了解决这个问题出现了数据库连接池的技术; C3P0连接池 使用步骤 1、导入jar包; 2、导入配置文件到src目录下;(配置文件会自动导入,但是名字必须是c3p0-config.xml或者c3p0-config-properties) 3、创建C3P0连接池对象; 4、获取连接; 5、使用连接;

weixin_46837969的博客 715

请尽可能地详细说明一个VLA项目的立项训练到落地的全流程

一个机器人VLA项目的全流程是一个复杂的系统工程,它深度融合了机器人学 (Robotics)计算机视觉 (CV)和自然语言处理 (NLP)。其核心挑战在于高质量数据的获取和从仿真到现实的有效迁移。与纯粹的软件AI项目相比,它增加了硬件、物理交互和安全性的维度,但其最终能让AI走出虚拟世界、在物理世界中产生实际价值,这也是其巨大的魅力所在。

具身机器人和通用AI 312

35、使用 Geo 创建 GitLab 的分布式只读副本

本文详细介绍了如何使用GitLab Geo功能创建分布式只读副本,涵盖数据库主从配置、SSH密钥查找方式更改、通过Web UI添加从节点、激活哈希存储及状态检查等关键步骤。同时提供了常见问题解答和配置流程图,帮助用户快速部署并维护Geo集群,实现跨地域的高效数据同步与高可用架构。

chair的专栏 84

druid定义 java使用_[数据库druid连接池实现]--Java版本

前言之前有介绍一篇关于自定义的数据库链接池实现,但是质量并不高。而且遭到博友的一脸嫌弃!确实,拿出来的东西就应该保证是正确的,或者质量高,否则很容易就误导了他人,显得TMD也不道德,所以今天专门重写之前的想法,当然,还有许多文章需要更新,后期我都会一一完善,希望对各位有一定的帮助。目前针对Java web应用使用的数据库链接池比较多也很杂,但稳定且好用的还是推荐阿里巴巴的druid(德鲁伊连接池)...

weixin_42469000的博客 557

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

MyBatis 使用阿里的Druid连接池

MyBatis默认提供了一个数据库连接池PooledDataSource,一般我们只需要在配置文件中配置,然后就可以使用 &lt;dataSource type="POOLED" &gt; &lt;property name="driver" value="${driver}"/&gt; &lt;property name="url" value=&q

Cloud-Future的博客 1万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

数据库连接池的使用 - Druid(德鲁伊)

1、数据库连接池 1.1概念 ​ 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高对数据库操作的性能。 面试题:什么是数据库连接池? 目前的数据库连接做法: ​ 需要链接数据就马上创建一个连接,使用完成之后,就将连接关闭了。下次...

weixin_41540362的博客 3196

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

数据库连接池(Druid、DBCP、C3P0)和Apache组织DBUtils工具类使用

数据库连接池(Druid、DBCP、C3P0)和Apache组织DBUtils工具类使用 第一节:自定义连接池 使用JDBC操作数据库,需要建立Connection,使用传统的JDBC操作需要每次创建Connection,创建Connection是一个非常性能和消耗时间的过程,我们需要在提高程序性能,那么就需要减少每次创建创建连接带来的负面影响,解决这个问题我们将利用池子概念,预先创建一些链接放入池子中,如果需要操作数据,不用创建新的Connection,只需要在池子中获取即可,使用完毕放入池子!这样就形

qq_37867421的博客 383

连接池原理、实现代码和Druid的使用案例

1.连接池原理 1.创建一个集合,用于存放连接 2.驱动加载 3.指定数量的连接对象,存入集合 4.从集合中拿出连接来使用,将该连接对象从集合中移除 5.连接释放:本质是将该连接对象放回集合 具体实现如下:(这里是使用了配置文件来存储配置的变量,所以多了一个加载配置文件的步骤) 2.简单连接池的实现 1.配置文件:db.properties; jdbc_driver=com.mysql.cj.jdbc.Driver jdbc_url=jdbc:mysql://localhost:3306/empdb?us

qq_42739776的博客 648

56_1数据库连接池【自定义连接池、Druid(德鲁伊) 数据库连接池】

数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。这项技术能明显提高了数据库操作的性能。

gangain的博客 1288

自定义连接池&C3P0&Druid

连接池 学习目标 能够理解连接池解决现状问题的原理(理解) 能够理解代理模式(不需要重点掌握) 能够使用动态代理(最好能搞懂) 能够使用C3P0连接池(必须掌握) 能够编写C3P0连接池工具类(必须掌握) 能够使用DRUID连接池(必须掌握) 第1章 自定义连接池 1.1 连接池概念 ​ 我们现实生活中每日三餐。我们并不会吃一餐饭就将碗丢掉,而是吃完饭后将碗放到碗柜中,下一餐接着使用。目的是重复利用碗,我们的数据库连接也可以重复使用,可以减少数据库连接的创建次数。提高数据库连接对象的使用率。 连接池的概

weixin_43575838的博客 349

MyBatis笔记Day03_Mybatis连接池_druid数据库连接池

MyBatis默认提供了一个数据库连接池PooledDataSource,只需要在配置文件中配置一下就可以 使用了。修改dataSource的type属性就可以了。 <environments default="mysql"> <!-- 配置mysql的环境 --> <environment id="mysql"> <!--配置事务类型--> <trans

ZM つ小灰灰的成长的博客 1497

连接池(C3P0 、DRUID)和DBUtils(简化jdbc的操作)

连接池和DBUtils 为什么要使用连接池 ​ Connection对象在JDBC使用的时候就会去创建一个对象,使用结束以后就会将这个对象给销毁了(close).每次创建和销毁对象都是耗时操作.需要使用连接池对其进行优化. 数据库的连接建立,开销比较大,所以在一开始就用一个池子来装若干个连接对象。 ​ 程序初始化的时候,初始化多个连接,将多个连接放入到池(集合)中.每次获取的时候,都可以直接从连接池中进行获取.使用结束以后,将连接归还到池中. 连接池原理【重点】 开始先使用集合存储若干个连接对象到集

weixin_41942838的博客 455

springboot整合druid连接池

引用下Druid介绍 DRUID是阿里巴巴开源平台上一个数据库连接池实现,它结合了C3P0、DBCP、PROXOOL等DB池的优点,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况,可以说是针对监控而生的DB连接池,据说是目前最好的连接池。 一、springboot项目pom配置 <dependency> <groupId&g...

diyangtun7591的博客 172
上一篇: Android入门笔记05
下一篇: Android入门笔记06
AnalogElectronic
博客等级 码龄9年 740粉丝 561原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值