Java线程和MySQL [英] Java Threads and MySQL
问题描述
我有一个需要MySQL身份验证的线程聊天服务器应用程序.
I have a threaded chat server application which requires MySQL authencation.
让1个类创建MySQL连接,保持该连接打开并让每个线程都使用该连接但使用自己的查询处理程序是最好的方法吗?
Is the best way to have 1 class create the MySQL connection, keep that connection open and let every thread use that connection but use own Query handler?
还是让所有线程与MySQL单独连接以进行身份验证会更好?
Or is it better to have all threads make a seperate connection to MySQL to authencate?
还是让1个类处理查询和连接更好?
Or is it better to let 1 class handle the queries AND connections?
我们正在寻找一个聊天服务器,该服务器应该能够处理多达10.000个连接/用户.
We are looking at a chatserver that should be able to handle upto 10.000 connections/users.
我现在正在使用c3p0,并且创建了它:
I am now using c3p0, and I created this:
public static void main(String[] args) throws PropertyVetoException
{
ComboPooledDataSource pool = new ComboPooledDataSource();
pool.setDriverClass("com.mysql.jdbc.Driver");
pool.setJdbcUrl("jdbc:mysql://localhost:3306/db");
pool.setUser("root");
pool.setPassword("pw");
pool.setMaxPoolSize(100);
pool.setMinPoolSize(10);
Database database = new Database(pool);
try
{
ResultSet rs = database.query("SELECT * FROM `users`");
while (rs.next()) {
System.out.println(rs.getString("userid"));
System.out.println(rs.getString("username"));
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
finally
{
database.close();
}
}
公共类数据库{
ComboPooledDataSource pool;
Connection conn;
ResultSet rs = null;
Statement st = null;
public Database (ComboPooledDataSource p_pool)
{
pool = p_pool;
}
public ResultSet query (String _query)
{
try {
conn = pool.getConnection();
st = conn.createStatement();
rs = st.executeQuery(_query);
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
return rs;
}
public void close ()
{
try {
st.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
这将是线程安全的吗?
推荐答案
您是否看过连接池?检出(例如) Apache DBCP 或
Have you looked at connection pooling ? Check out (for example) Apache DBCP or C3P0.
简而言之,连接池意味着使用经过身份验证的连接池,并根据请求将免费连接传递给您.您可以根据需要配置连接数.当您关闭连接时,它实际上已返回到池中并可供其他客户端使用.由于该池负责身份验证和连接管理,因此在您的情况下使工作变得相对轻松.
Briefly, connection pooling means that a pool of authenticated connections are used, and free connections are passed to you on request. You can configure the number of connections as appropriate. When you close a connection, it's actually returned to the pool and made available for another client. It makes life relatively easy in your scenario, since the pool looks after the authentication and connection management.
这篇关于Java线程和MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!