Home Database Mysql Tutorial 项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

Jun 07, 2016 pm 03:35 PM
d log4j optimization database data source connect Configuration Refactor project

作者 :泥沙砖瓦浆木匠 网站 : http://blog.csdn.net/jeffli1993 个人签名 : 打算起手不凡写出鸿篇巨作的人,往往坚持不了完成第一章节。 交流QQ群 :【编程之美 365234583】http://qm.qq.com/cgi-bin/qm/qr?k=FhFAoaWwjP29_AonqzL0rpdQAjjqlHQQ 如果我的

作者:泥沙砖瓦浆木匠
网站
http://blog.csdn.net/jeffli1993
个人签名打算起手不凡写出鸿篇巨作的人,往往坚持不了完成第一章节。

交流QQ群:【编程之美 365234583】http://qm.qq.com/cgi-bin/qm/qr?k=FhFAoaWwjP29_AonqzL0rpdQAjjqlHQQ

如果我的帮到了你,是否乐意捐助一下或请一杯啤酒也好呢?有你支持,干的更好~

点这参与众筹 我的支付宝:13958686678

一、 前言

  泥瓦匠又和大家见面了,最近两天我在Code Review ,顺便代码小小的Refactoring(重构)下。先了解这个项目吧,这次解决的是数据源配置优化。因为这web项目中配置数据源的地方很多。例如JDBC要配置数据源,Mybatis要配置数据源,Quartz定时任务要配置数据源,还有Log4j存记录到数据库也要配置…

  如题目,兴许大家的疑惑看了前面的说明会明白。这次给大家带来的 数据源配置与优化:log4j 配置数据库连接池Druid。

  提纲:

  • 二、准备知识
  • 三、正文 开始动手吧
  •      、配置文件
  •      、建数据表
  •      、核心代码讲解
  • 四、结论及下载

二、准备知识

  泥瓦匠也是怕自己说不清楚,又不想把Log4j 和 Durid介绍个遍。那样会太麻烦。这次主要是项目实战。所以泥瓦匠也不罗嗦知识准备这块也就是点到为止。

  Log4j 简介
  在应用程序中添加日志记录总的来说基于三个目的
    监视代码中变量的变化情况,周期性的记录到文件中供其他应用进行统计分析工作;
    跟踪代码运行时轨迹,作为日后审计的依据;
    担当集成开发环境中的调试器的作用,向文件或控制台打印代码的调试信息。
  它支持将日志信息输入到数据库,这次我们一Mysql为例说明。我们需要Log4j来将调试信息、操作信息等记录下来,以便后面的审计,这些日志信息包括用户ID、用户姓名、操作类、路径、方法、操作时间、日志信息。

  Druid 简介

  Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。不多多介绍了,阿里牛人作品必须精品。详细介绍在:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

 

  泥瓦匠的任务很简单,目的是为了数据源配置优化,实现数据源配置的唯一性。泥瓦匠也画了草图,曾经被人说成画图画出鬼画符的我告诉大家:没事,越做越好。如图,设计简单草图就是这样的。

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

结论:一个项目的配置文件要保持唯一性,就是数据源配置的唯一性。

 

三、正文 开始动手吧

  开始弄吧,为了写这个东西。我就也搞了个demo项目。泥瓦匠很辛苦的,哈哈送钱的上面支付宝哦。哈哈,泡了杯水,准备说这个项目了。下面,泥瓦匠先给出这个项目的结构图,这样我待会讲起来不怎么累。逻辑性比较强吧。如图:

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

  上面很清楚的写着我需要完成的功能模块。最后那个test,是一个测试的servlet类。大家一看就明白。我先从配置文件说起吧。

配置文件 :

  dbConfig.properties 记录的是最基础的db配置:url name psd 等,代码如下:

1

2

3

4

5

6

7

8

database.vendor = mysql

db_url = jdbc:mysql://localhost:3307/test

driverClassName= com.mysql.jdbc.Driver

db_user = root

db_password = 123456

showsql= false

devMode = true

validationQuery=SELECT 1

  log4j.properties则是日志的配置,但日志的配置中有一点注意的是如下:

1

2

3

4

5

6

7

8

9

10

log4j.rootLogger=debug,appender1

log4j.appender.appender1=org.apache.log4j.ConsoleAppender

log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout

log4j.logger.test=INFO, db

 

# log db setting

log4j.appender.db=org.nsg.dbsetting.MyJDBCAppender

log4j.appender.db.BufferSize=1

log4j.appender.db.sql=insert into operate_log(handclass,method,createtime,loglevel,logmsg) values ('%C','%M','%d{yyyy-MM-dd HH\:mm\:ss}','%p','%m')

log4j.appender.db.layout=org.apache.log4j.PatternLayout

  在这里,我们要注意两点:

一、设置我们包的下的logger权限,并给予存数据库的权限。

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

二、db的实现的应用要为你写的引用类。

1

2

# log db setting

log4j.appender.db=org.nsg.dbsetting.MyJDBCAppender

建数据表 :

然后我们要根据上面配置文件中写的数据库和表格我们要对应的建一个名为test的数据库和一张名为operate_log的表。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

/*

Navicat MySQL Data Transfer

 

Source Server         : Mysql

Source Server Version : 50617

Source Host           : localhost:3307

Source Database       : test

 

Target Server Type    : MYSQL

Target Server Version : 50617

File Encoding         : 65001

 

Date: 2014-12-08 18:46:21

*/

 

SET FOREIGN_KEY_CHECKS=0;

 

-- ----------------------------

-- Table structure for operate_log

-- ----------------------------

DROP TABLE IF EXISTS `operate_log`;

CREATE TABLE `operate_log` (

  `log_id` int(11) NOT NULL AUTO_INCREMENT,

  `handclass` varchar(100) DEFAULT NULL,

  `method` varchar(100) DEFAULT NULL,

  `createtime` varchar(100) DEFAULT NULL,

  `loglevel` varchar(20) DEFAULT NULL,

  `logmsg` text,

  PRIMARY KEY (`log_id`)

) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;

这样我们就可以开始写代码了,泥瓦匠是一个很细节的人。这次博客,我主要是讲下代码中的核心点。因为后面我会把项目提供给你们下载。所以,这里点到为止。

泥瓦匠说:点到为止,所谓师父领进门,修行在个人啊。

核心代码讲解:

  MyJDBCAppender.java 用于Log4j的数据库Session管理[连接池用Druid]。这个肯定是我们得核心思想。这里我就继承了log4j提供的org.apache.log4j.jdbc.JDBCAppender;然后只要简单的重写了closeConnection和getConnection方法。如果获取Druid数据库源对象异常的话,我还写了个 取消初始化 的方法uninitialize。代码这边也贴出下,方便大家观看:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

package org.nsg.dbsetting;

 

import java.sql.Connection;

import java.sql.SQLException;

import java.util.Properties;

 

import org.apache.log4j.jdbc.JDBCAppender;

import org.apache.log4j.spi.ErrorCode;

import org.nsg.constant.PropertiesConst;

import org.nsg.exception.JdbcException;

import org.nsg.util.MyProperties;

import org.nsg.util.PropertiesUtil;

 

import com.alibaba.druid.pool.DruidDataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

 

/**

 * @Description  MyJDBCAppender.java

 * 用于Log4j的数据库Session管理[连接池用Druid]

 * @author 泥沙砖瓦浆木匠

 * @date 2014年12月7日下午1:50:56

 * @version 1.0

 */

public class MyJDBCAppender extends JDBCAppender

{

    /* Druid数据源 */

    private DruidDataSource dataSource;

     

    public MyJDBCAppender()

    {

        super();

    }

     

    @Override

    protected void closeConnection(Connection con)

    {

        try

        {

            /* 如果数据库连接对象不为空和没有被关闭的话,关闭数据库连接 */

            if ( con != null && !con.isClosed())

                con.close();

             

        }

        catch (SQLException e)

        {

            errorHandler.error("Error closing MyJDBCAppender.closeConnection() 's connection",e,ErrorCode.GENERIC_FAILURE);

        }

    }

 

    @Override

    protected Connection getConnection() throws SQLException

    {

        /* 获取数据库配置property */

        MyProperties properties = PropertiesUtil.loadPropertyFile(PropertiesConst.DB_CONFIG);

        String className = String.valueOf(properties.getProperty("driverClassName",""));

        String connUrl = String.valueOf(properties.getProperty("db_url",""));

        String uname = String.valueOf(properties.getProperty("db_user",""));

        String psw = String.valueOf(properties.getProperty("db_password",""));

 

        System.out.println(className);

        System.out.println(connUrl);

        System.out.println(uname);

        System.out.println(psw);

         

        Properties result = new Properties();

        result.put("driverClassName",className);

        result.put("url",connUrl);

        result.put("username",uname);

        result.put("password",psw);

         

        /* 其他配置 自然你也可以自己写property 然后获取set */

        result.put("maxActive","30");

        result.put("minIdle","3");

 

        try

        {

            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(result);

        }

        catch (Exception e)

        {

            /* Druid数据库源对象产生失败后,取消初始化 */

            try {uninitialize();} catch(Exception e2) {}

            throw new JdbcException(e);

        }

         

        return dataSource.getConnection();

    }

 

    /* 取消初始化 */

    public void uninitialize()

    {

        try

        {

            if (dataSource != null)

                dataSource.close();

        }

        catch (Exception e)

        {

            throw new JdbcException(String.format("MyJDBCAppender uninitialize fail (%s)",e));

        }

        finally

        {

            super.close();

        }

    }

     

}

  值得注意的一点是,泥瓦匠为了方便,所以在其中的地方没有获取druid连接池的配置。而是直接写了下面:

1

2

3

/* 其他配置 自然你也可以自己写property 然后获取set */

        result.put("maxActive","30");

        result.put("minIdle","3");

  其实这样写是不好了,我们可以写一个druid.properties然后将连接池的配置放入其中。获取set,for循环set即可。这边我就不实现了。很简单哦,泥瓦匠相信你们。

 

最后我演示下,示例代码:放到tomcat7上,然后运行访问

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

看到控制台刷出来两条信息,因为我门设置的是log4j.logger.test=INFO, db。

然后我们去查看数据库,这边我用Navicat:

项目重构之数据源配置与优化:log4j 配置数据库连接池Druid,并

 

四、结论及下载

结论:重构很有意思,慢慢来,一点一点来,就行了。细节成就未来。

下载链接:

http://pan.baidu.com/s/1hqKN0Le

如以上文章或链接对你有帮助的话,别忘了在文章按钮或到页面右下角点击 “赞一个” 按钮哦。你也可以点击页面右边“分享”悬浮按钮哦,让更多的人阅读这篇文章

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use database callback functions in Golang? How to use database callback functions in Golang? Jun 03, 2024 pm 02:20 PM

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

How to connect to remote database using Golang? How to connect to remote database using Golang? Jun 01, 2024 pm 08:31 PM

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

PHP connections to different databases: MySQL, PostgreSQL, Oracle and more PHP connections to different databases: MySQL, PostgreSQL, Oracle and more Jun 01, 2024 pm 03:02 PM

PHP database connection guide: MySQL: Install the MySQLi extension and create a connection (servername, username, password, dbname). PostgreSQL: Install the PgSQL extension and create a connection (host, dbname, user, password). Oracle: Install the OracleOCI8 extension and create a connection (servername, username, password). Practical case: Obtain MySQL data, PostgreSQL query, OracleOCI8 update record.

See all articles