使用代理对象实现数据库的连接池

搭建MySQL数据库

tar -xvf mysql-5.7.19-1.el7.x86_64.rpm-bundle.tar

在虚拟机上安装MySQL:

yum remove mysql-libs 
rpm -ivh mysql-community-common-5.7.19-1.el7.x86_64.rpm
rpm -ivh mysql-community-libs-5.7.19-1.el7.x86_64.rpm
rpm -ivh mysql-community-client-5.7.19-1.el7.x86_64.rpm
rpm -ivh mysql-community-server-5.7.19-1.el7.x86_64.rpm
rpm -ivh mysql-community-devel-5.7.19-1.el7.x86_64.rpm  (可选)

启动MySQL

service mysqld start
systemctl start mysqld.service

查看root用户的密码

cat /var/log/mysqld.log | grep password

登录后修改密码

alter user 'root'@'localhost' identified by 'Welcome_1';

MySQL数据库的配置
创建一个新的数据库

create database hive;

创建一个新的用户

create user 'hiveowner'@'%' identified by 'Welcome_1';

给该用户授权

grant all on hive.* TO 'hiveowner'@'%'; 
grant all on hive.* TO 'hiveowner'@'localhost' identified by 'Welcome_1';           

使用代理对象实现数据库的连接池_第1张图片

package datasource;

import java.sql.Connection;
import java.sql.SQLException;

public class TestDataSourceMain {
    public static void main(String[] args) throws Exception {
        //从连接池中获取链接 使用完后  释放链接
        MyDataSourcePool pool = new MyDataSourcePool();
        for(int i=0;i<11;i++){
            Connection conn = pool.getConnection();//得到的链接是真正的数据库链接
            System.out.println("第"+i+"个链接,是"+ conn);
            conn.close(); //把数据库的链接还给了数据库,而不是连接池
        }
    }
}
package datasource;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;
import javax.sql.DataSource;

public class MyDataSourcePool implements DataSource {
    //初始化连接池,放入10个链接
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://192.168.157.111:3306/hive";
    private static String user = "hiveowner";
    private static String password = "Welcome_1";
    //定义一个链表来保存10个链接
    private static LinkedList dataSource = new LinkedList<>();
    static{
        try{
            //注册驱动
            Class.forName(driver);
            for(int i=0;i<10;i++){
                dataSource.add(DriverManager.getConnection(url, user, password));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
//      // 从连接池中返回一个连接
//      if(dataSource.size() > 0){
//          //有一个连接,直接返回该链接
//          return dataSource.removeFirst();
//      }else{
//          throw new SQLException("系统忙,请稍后.....");
//      }       
        if(dataSource.size() >0){
            //得到一个连接,是真正的对象
            Connection conn = dataSource.removeFirst();

            //生成代理对象
            Connection proxy = (Connection) Proxy.newProxyInstance(MyDataSourcePool.class.getClassLoader(), 
                                   conn.getClass().getInterfaces(), 
                                   new InvocationHandler() {

                                    @Override
                                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                        // 重写close的逻辑
                                        if(method.getName().equals("close")){
                                            //将链接还给连接池
                                            dataSource.add(conn);
                                            System.out.println("链接已经还池.....");
                                            return null;
                                        }else{
                                            return method.invoke(conn, args);
                                        }
                                    }
                                });

            //返回代理对象
            return proxy;
        }else{
            throw new SQLException("系统忙,请稍后.....");
        }

    }   


    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public  T unwrap(Class iface) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isWrapperFor(Class iface) throws SQLException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

}

你可能感兴趣的:(大数据笔记)