记录 动态代理doris

文章讲述了作者在将MySQL8的jar包与Doris集成时遇到内存持续增长的问题,通过尝试不同方法发现手动引入的jar包没有正确释放,最后找到了通过反射加载Driver类来解决问题的方法。
摘要由CSDN通过智能技术生成

黏贴主要代码

刚开始想着是  本地使用的是 mysql8的jar 包 ,可能和 doris 有冲突索引手动引入java包

    public static Connection getUnPooledConnection_Doris(DataSourceDto dataSource) throws SQLException {
        String jarFilePath =dataSource.getDictPath();
        String className = "com.mysql.jdbc.Driver";
        try (URLClassLoader loader = new URLClassLoader(new URL[]{new URL(jarFilePath)})) {
            Class<?> driverClass = Class.forName(className, true, loader);
            Driver driver = (Driver) driverClass.newInstance();
            Properties info = new Properties();
            info.put("user", dataSource.getUsername());
            info.put("password", dataSource.getPassword());

            Connection connection = driver.connect(dataSource.getJdbcUrl(), info);

            if (connection != null) {
                LOGGER.info("Connected to database version: {}", connection.getMetaData().getDatabaseProductVersion());
                LOGGER.info("Using JDBC driver version: {}", connection.getMetaData().getDriverVersion());
            }

            return connection;
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | MalformedURLException e) {
            throw new SQLException("Failed to load JDBC driver or establish a connection", e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

但是线上运行发现,内存一直在增加,手动引入的jar不释放,尝试很多办法依旧没见成效

偶然发现 

可以class 给 搞出来  简单还省事

 public Connection getUnPooledConnection_Doris(DataSourceDto dataSource) throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException, MalformedURLException {
        String className = "com.mysql.jdbc.Driver"; // MySQL 5.x 的驱动程序类名,MySQL 8.x 使用另一个类名
            Class<?> CA = Class.forName(className);
            Driver driver = (Driver) CA.newInstance();
            Connection connection = null;
            Properties info = new Properties();
            info.put("user", dataSource.getUsername());
            info.put("password", dataSource.getPassword());
            connection = driver.connect(dataSource.getJdbcUrl(), info);
            System.out.println(connection.getMetaData().getDatabaseProductVersion());
            System.out.println(connection.getMetaData().getDriverVersion());
            return connection;

    }

记录下-学艺不精,还得加油

当时参考网上大佬文章  大佬代码如下

import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anjiplus.template.gaea.business.code.ResponseCode;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class test {


    public static void main(String[] args) {
        Connection pooledConnection = null;

        try{
            Thread.sleep(10000);

            int count = 0;
            while (true) {
                System.out.println("start");
                String dir = "jar:file:D:/jar/mysql-connector-java-5.1.47.jar!/";
                URL url = new URL(dir);
                URL[] urls2 = {url};
                MyUrlClassLoader myUrlClassLoader = new MyUrlClassLoader(urls2);
                Class<?> CA = myUrlClassLoader.loadClass("com.mysql.jdbc.Driver");
                Driver driver = (Driver) CA.newInstance();
                Properties info = new Properties();
                info.put("user", "root");
                info.put("password", "xxx");
                Connection connection = driver.connect("jdbc:mysql://xxxx:9030/scv", info);
                System.out.println("--------------------"+connection.getMetaData().getDatabaseProductVersion());
                System.out.println("--------------------"+connection.getMetaData().getDriverVersion());
                pooledConnection = connection;
                PreparedStatement statement = pooledConnection.prepareStatement(" select * from  wms_inbound");

                ResultSet rs = statement.executeQuery();
                int columnCount = rs.getMetaData().getColumnCount();
                List<String> columns = new ArrayList<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = rs.getMetaData().getColumnLabel(i);
                    columns.add(columnName);
                }
                List<JSONObject> list = new ArrayList<>();
                while (rs.next()) {
                    JSONObject jo = new JSONObject();
                    columns.forEach(t -> {
                        try {
                            Object value = rs.getObject(t);
                            //数据类型转换
                            Object result = dealResult(value);
                            jo.put(t, result);
                        } catch (SQLException throwable) {
//                            log.error("error",throwable);
                            throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_SQL_ERROR, throwable.getMessage());
                        }
                    });
                    list.add(jo);
                }


                System.out.println(list.toString());


                System.out.println("done");
//                Thread.sleep(5000);
                myUrlClassLoader = null;
                System.out.println("release");
                System.gc();

                ++ count;
                if(count > 5)
                    break;
            }

            System.out.println("alldone");
        } catch (Exception e) {
            System.out.println("found exception");
            e.printStackTrace();
        } catch (Throwable throwable) {
            System.out.println("found throwable");
            throwable.printStackTrace();
        }


    }



    private static Object dealResult(Object result) throws SQLException {
        if (null == result) {
            return result;
        }
        String type = result.getClass().getName();
        if ("oracle.sql.TIMESTAMP".equals(type)) {
            //oracle.sql.TIMESTAMP处理逻辑
            return new Date((Long) JSONObject.toJSON(result));
        }

        return result;
    }


    private static class MyUrlClassLoader extends URLClassLoader {

        public MyUrlClassLoader(URL[] urls) {
            super(urls);
        }

        @Override
        protected Class<?> findClass(final String name) throws ClassNotFoundException {
            return super.findClass(name);
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("回收");
            super.finalize();
        }
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值