mysql与redis快速插入数据

1.多线程的使用

java最优性能线程数与cpu线程数有关,cpu每个线程同时只能做一件事,但java程序运行时间分为计算时间与非计算时间如IO读取等操作耗时,
开启2-3倍的cpu线程数的线程一般情况下是追求性能优先的最优选择,因为过多的线程数会浪费一些资源在cpu线程的切换上

2.mySql批量插入

mySql快速批量插入比较合适的方法是通过jdbc的批处理插入数据,代码如下:

	public void insertBatch(int i) {
		/* 数据源 */
		Connection connection = null;
		try {
			// 1.加载MySQL的驱动
			Class.forName("com.mysql.jdbc.Driver");
			/* 连接数据库的参数 */
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
					"root");
			/* 插入的sql */
			String sql = "INSERT into sys_user(user_lid,user_state) VALUES(?,?)";
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			/* 循环插入 */
			for (int i = count * 10000 + 1; i <= count * 10000 + 10000; i++) {
				preparedStatement.setString(1, i + "");
				preparedStatement.setInt(2, 1);
				preparedStatement.addBatch();// 把数据放入缓存区

				if (i % 10000 == 0) {
					// 刷新缓存区
					preparedStatement.executeBatch();
					preparedStatement.clearBatch();// 清除之前的数据
				}

			}
			// 刷新缓存区
			preparedStatement.executeBatch();
			preparedStatement.close();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

		}
	}

如开启事务并手动提交会效率更高

3.Redis批量插入

	public static void main(String[] args) throws Exception {
		Jedis jedis = new Jedis("localhost", 6379);
		//redis密码
		jedis.auth("root");
		//构建Pipeline对象
		Pipeline pipelined = jedis.pipelined();
		for (int i = 1; i <= 100000; i++) {
			pipelined.set(i + ":token", i + "");
			pipelined.set("token:" + i, i + "");
		}
		//执行Pipeline对象
		pipelined.sync();
		//关闭连接
		jedis.close();
	}

猜你喜欢

转载自blog.csdn.net/qq_24516549/article/details/84455482