Spring-_-Bear 个人开发工具类
Posted Spring-_-Bear
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring-_-Bear 个人开发工具类相关的知识,希望对你有一定的参考价值。
一、BaseDao
import com.bear.tools.db.util.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* @author Spring-_-Bear
* @datetime 2022/2/15 22:47
*/
public abstract class BaseDao
private final QueryRunner queryRunner = new QueryRunner();
/**
* 执行 insert、update、delete 语句
*
* @param sql sql
* @param args sql 实参
* @return 执行语句受影响的行数
*/
public int update(String sql, Object... args)
Connection connection = null;
try
connection = JdbcUtils.getConnection();
return queryRunner.update(connection, sql, args);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtils.close(connection);
return -1;
/**
* 查询数据库表的一条记录
*
* @param clazz JavaBean class 对象
* @param sql sql
* @param args sql 实参
* @param <T> 返回类型泛型
* @return 一条记录
*/
public <T> T getRecord(Class<T> clazz, String sql, Object... args)
Connection connection = null;
try
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtils.close(connection);
return null;
/**
* 查询返回多条数据库表记录
*
* @param clazz JavaBean 的 class 对象
* @param sql sql
* @param args sql 实参
* @param <T> 返回类型的泛型
* @return 多条记录
*/
public <T> List<T> listRecord(Class<T> clazz, String sql, Object... args)
Connection connection = null;
try
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtils.close(connection);
return null;
/**
* 查询返回单个数组
*
* @param sql sql
* @param args sql 实参
* @return 某个单元格对象
*/
public Object getSingleValue(String sql, Object... args)
Connection connection = null;
try
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new ScalarHandler(), args);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtils.close(connection);
return null;
二、BaseServlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Spring-_-Bear
* @datetime 2022/3/1 20:17
*/
public class BaseServlet extends HttpServlet
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
String action = req.getParameter("action");
try
// 通过反射机制获取对应的方法对象
Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// 调用方法
declaredMethod.invoke(this, req, resp);
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
e.printStackTrace();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
String action = req.getParameter("action");
try
// 通过反射机制获取对应的方法对象
Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// 调用方法
declaredMethod.invoke(this, req, resp);
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
e.printStackTrace();
三、ThreadPoolUtil
import java.util.concurrent.*;
/**
* @author Spring-_-Bear
* @datetime 2021-12-18 20:47
*/
public class ThreadPoolUtil
/**
* 线程池服务
*/
private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(
12,
24,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(512),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
/**
* 执行线程任务
*
* @param task 线程任务
*/
public static void execute(Runnable task)
EXECUTOR_SERVICE.execute(task);
/**
* 销毁线程池
*/
public static void shutdown()
EXECUTOR_SERVICE.shutdown();
四、JdbcUtil
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* @author Spring-_-Bear
* @datetime 2022/2/15 22:40
*/
public class JdbcUtils
static DataSource dataSource;
// 读取配置文件,获取配置信息
static
Properties properties = new Properties();
try
InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
catch (Exception e)
e.printStackTrace();
/**
* 从数据库连接池中获取一个数据库连接对象
*
* @return Connection
* @throws SQLException exception
*/
public static Connection getConnection() throws SQLException
return dataSource.getConnection();
/**
* 归还数据库连接对象到数据库连接池
*
* @param connection Connection
*/
public static void close(Connection connection)
try
if (connection != null)
connection.close();
catch (SQLException e)
throw new RuntimeException(e);
五、DatabaseUtil
import java.io.*;
import java.util.Properties;
/**
* @author Spring-_-Bear
* @datetime 2021-12-19 21:39
*/
public class DatabaseUtil
private static final String PATH = "resources\\\\druid.properties";
private static String serverIp;
private static String username;
private static String password;
private static String dbName;
static
Properties properties = new Properties();
try
properties.load(new FileInputStream(PATH));
serverIp = properties.getProperty("serverIp");
username = properties.getProperty("username");
password = properties.getProperty("password");
dbName = "ebrss";
catch (IOException e)
e.printStackTrace();
/**
* 备份 mysql 数据库
*
* @param fileSavePath 备份文件保存路径
*/
public static void databaseBackup(String fileSavePath)
// 组合备份 MySQL 数据库命令并发送到控制台执行
String command = "mysqldump -h" + serverIp + " -u" + username + " -p" + password + " -B " + dbName + " > " + fileSavePath + "\\\\" + dbName + ".sql";
try
Runtime.getRuntime().exec("cmd /c" + command);
catch (IOException e)
e.printStackTrace();
六、AppendObjectOutputStream
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
* 解决 java.io.StreamCorruptedException: invalid type code: AC 异常
* 原因分析参考博客:https://blog.csdn.net/weixin_51008866/article/details/121061149
*
* @author Spring-_-Bear
* @version 2021-10-30 21:48
*/
public class AppendObjectOutputStream extends ObjectOutputStream
private static File file = null;
public static void setFile(File file)
AppendObjectOutputStream.file = file;
/**
* 调用父类的构造器,初始化父类
*
* @param file The path of the file
* @throws IOException I/O异常
*/
public AppendObjectOutputStream(File file) throws IOException
super(new FileOutputStream(file, true));
/**
* 重写父类的 writeSteamHeader() 方法以实现文件中只存在一个StreamHeader
*
* @throws IOException I/O 异常
*/
@Override
public void writeStreamHeader() throws IOException
// 如果文件为空直接写入 StreamHeader
if (file == null)
super.writeStreamHeader();
else
// 文件长度为0即文件中没有内容时也写入 StreamHeader
if (file.length() == 0)
super.writeStreamHeader();
else
// 文件存在且文件中存在内容,则说明文件中已经存在了一个 StreamHeader
// 则调用父类的 reset() 方法保证文件中只存在一个 StreamHeader
this.reset();
七、FileUtil
import java.io.*;
import java.util.Objects;
/**
* @author Spring-_-Bear
* @datetime 2021-12-19 10:06
*/
public class FileUtil
/**
* 从磁盘加载指定路径的文件并得到文件字节数据
*
* @param filePath 文件路径
* @return 文件字节数据或 null
*/
public static byte[] getFileDataFromDisk(String filePath)
File file = new File(filePath);
if (!file.exists() && file.isFile())
return null;
ByteArrayOutputStream byteArrayOutputStream = null;
FileInputStream fileInputStream = null;
try
byteArrayOutputStream = new ByteArrayOutputStream();
fileInputStream = new FileInputStream(file);
int readLen;
byte[] buf = new byte[1024];
// 从文件中读取字节数据
while ((readLen = fileInputStream.read(buf)) != -1)
byteArrayOutputStream.write(buf, 0, readLen);
return byteArrayOutputStream.toByteArray();
catch (IOException e)
e.printStackTrace();
return null;
finally
try
Objects.requireNonNull(byteArrayOutputStream).close();
Objects.requireNonNull(fileInputStream).close();
catch (IOException e)
e.printStackTrace();
/**
* 将文件字节信息保存到指定的磁盘路径,磁盘路径应包含文件名和文件类型
*
* @param fileData 文件字节数据
* @param savePath 文件保存全路径
* @return true - 保存成功
*/
public static boolean saveFileToDisk(byte[] fileData, String savePath)
if (fileData == null)
return false;
FileOutputStream fileOutputStream = null;
try
fileOutputStream = new FileOutputStream(savePath);
fileOutputStream.write(fileData);
fileOutputStream.flush();
return true;
catch (IOException e)
e.printStackTrace();
return false;
finally
try
Objects.requireNonNull(fileOutputStream).close();
catch (IOException e)
e.printStackTrace();
以上是关于Spring-_-Bear 个人开发工具类的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 385D - Bear and Floodlight
阶段3 2.Spring_07.银行转账案例_4 编写事务管理工具类并分析连接和线程解绑