Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Well i've kept this to myself for a while now, This is one of the first ones i made (I have revised it before posting), so it may have a few small bugs, Also this is mostly untested, only briefly for a minute or 2.
- Features:
- Creates connections on-demand (Not the best for remote connections, which noone SHOULD be using anyways)
- Cleans up inactive connections
- Executes in a multi-thread environment for longer queries
- Multiple database support
- Easy to use settings
- Spoiler for Code:
- MySQL.java
- (Note: The stale connection time should not be changed unless it is still picking up stale connections, in that case, try 30000ms)
- Code:
- package org.hyperion.rs2.net.mysql;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /**
- *
- * @author Nicole <nicole@rune-server.org>
- *
- * @version 1.0
- *
- */
- public class MySQL {
- public static final String HOST = "localhost";
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
- public static final String[] DATABASES = {"database"};
- public static final String HOST_BASE = "jdbc:mysql://";
- public static final int MAX_CONNECTIONS = 5; //More for higher query counts
- public static final int THREAD_COUNT = 1; //Change this to suit your needs
- public static final int STALE_CONNECTION = 60000;
- public static final String DRIVER = "org.gjt.mm.mysql.Driver";
- private ExecutorService workerService = Executors.newFixedThreadPool(THREAD_COUNT);
- private MySQLConnectionPool[] pools;
- public MySQL() {
- try {
- Class.forName(DRIVER);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- pools = new MySQLConnectionPool[DATABASES.length];
- for(int i = 0; i < DATABASES.length; i++) {
- pools[i] = new MySQLConnectionPool(MAX_CONNECTIONS);
- pools[i].addDetail("url", parseURL(DATABASES[i]))
- .addDetail("user", USERNAME)
- .addDetail("password", PASSWORD);
- }
- }
- public void cleanup() {
- for(MySQLConnectionPool pool : getPools()) {
- pool.cleanConnections();
- }
- }
- public MySQLConnectionPool getPool(int index) {
- return pools[index];
- }
- public MySQLConnectionPool[] getPools() {
- return pools;
- }
- public ExecutorService getWorker() {
- return workerService;
- }
- public String parseURL(String database) {
- StringBuilder builder = new StringBuilder();
- builder.append(HOST_BASE);
- builder.append(HOST);
- builder.append("/");
- builder.append(database);
- return builder.toString();
- }
- public void shutdown() {
- for(int i = 0; i < pools.length; i++) {
- for(int il = 0; il < pools[i].getPool().size(); il++) {
- try {
- pools[i].getPool().get(il).getConnection().close();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- MySQLConnectionPool.java
- Code:
- package org.hyperion.rs2.net.mysql;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- /**
- *
- * @author Nicole <nicole@rune-server.org>
- *
- * @version 1.0
- *
- */
- public class MySQLConnectionPool {
- private HashMap<String, String> details = new HashMap<String, String>();
- private ArrayList<PoolConnection> pool;
- public MySQLConnectionPool(int numconn) {
- pool = new ArrayList<PoolConnection>(numconn);
- }
- public MySQLConnectionPool addDetail(String key, String value) {
- details.put(key, value);
- return this;
- }
- public void cleanConnections() {
- Iterator<PoolConnection> it$ = pool.iterator();
- long time = System.currentTimeMillis();
- while(it$.hasNext()) {
- PoolConnection c = it$.next();
- try {
- if(time - c.getLastUse() >= MySQL.STALE_CONNECTION
- || c.getConnection().isClosed()) {
- if(!c.getConnection().isClosed()) {
- c.getConnection().close();
- }
- it$.remove();
- }
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
- public PoolConnection getFreeConnection() {
- PoolConnection c;
- for(int i = 0; i < pool.size(); i++) {
- c = pool.get(i);
- if(c.borrow()) {
- return c;
- }
- }
- c = new PoolConnection();
- try {
- c.setConnection(DriverManager.getConnection(details.get("url"),
- details.get("user"), details.get("password")));
- } catch (SQLException e) {
- e.printStackTrace();
- }
- c.borrow();
- pool.add(c);
- return c;
- }
- public ArrayList<PoolConnection> getPool() {
- return pool;
- }
- }
- PoolConnection.java
- Code:
- package org.hyperion.rs2.net.mysql;
- import java.sql.Connection;
- import java.sql.SQLException;
- /**
- *
- * @author Nicole <nicole@rune-server.org>
- *
- * @version 1.0
- *
- */
- public class PoolConnection {
- private Connection connection;
- private boolean inUse = false;
- private long lastUse = System.currentTimeMillis();
- public PoolConnection() {
- }
- public boolean borrow() {
- try {
- boolean inuse = (!inUse && !connection.isClosed());
- if(!inuse) {
- setUsed(true);
- }
- return inuse;
- } catch (SQLException e) {
- e.printStackTrace();
- }
- return false;
- }
- public Connection getConnection() {
- return connection;
- }
- public long getLastUse() {
- return lastUse;
- }
- public boolean isInUse() {
- return inUse;
- }
- public void release() {
- setUsed(false);
- }
- public PoolConnection setConnection(Connection connection) {
- this.connection = connection;
- return this;
- }
- public void setUsed(boolean bool) {
- inUse = bool;
- if(!bool) {
- lastUse = System.currentTimeMillis();
- }
- }
- }
- MySQLResultCallable.java
- Code:
- package org.hyperion.rs2.net.mysql;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.concurrent.Callable;
- import org.hyperion.rs2.model.World;
- /**
- *
- * @author Nicole <nicole@rune-server.org>
- *
- * @version 1.0
- *
- */
- public class MySQLResultCallable implements Callable<ResultSet> {
- private String query;
- private int pool;
- public MySQLResultCallable(int pool, String query) {
- this.query = query;
- this.pool = pool;
- }
- @Override
- public ResultSet call() throws Exception {
- PoolConnection connection = World.getWorld().getMySQLHandler().getPool(pool).getFreeConnection();
- if(connection == null)
- throw new Exception("Unable to use/create a MySQL connection, Please make sure the MySQL server is running and accepting connections.");
- Statement stmt = connection.getConnection().createStatement();
- stmt.execute(query);
- connection.release();
- return stmt.getResultSet();
- }
- }
- Usage:
- Note: In all of these, editing 0 to the database index (According to the databases array, 0, 1, 2 etc), and also change the location of the instance.
- Inserting:
- Code:
- try {
- MySQLResultCallable query = new MySQLResultCallable(0, "INSERT INTO database VALUES('hi', 'hi there :P')");
- Future<ResultSet> future = World.getWorld().getMySQLHandler().getWorker().submit(query);
- future.get(); //Result set doesn't need to be closed, because we are not selecting anything.
- } catch (Exception e) {
- e.printStackTrace();
- }
- Selecting:
- Code:
- try {
- MySQLResultCallable query = new MySQLResultCallable(0, "SELECT * FROM database");
- Future<ResultSet> future = World.getWorld().getMySQLHandler().getWorker().submit(query);
- ResultSet rs = future.get();
- while (rs.next()) {
- String somefield = rs.getString("label"); //column label
- String somefield2 = rs.getString(0); //column index
- int somefield3 = rs.getInt("label"); //column label
- int somefield4 = rs.getInt(0); //column index
- //Do whatever with the data
- }
- rs.close(); //MAKE SURE to close the result set to free up memory
- } catch(Exception e) {
- e.printStackTrace();
- }
- Cleaning up connections:
- Code:
- new Thread(new Runnable() {
- public void run() {
- while(true) {
- World.getWorld().getMySQLHandler().cleanup();
- try {
- Thread.sleep(1000);
- } catch(Exception e) {
- break;
- }
- }
- }
- }).start();
- There you go, change imports to suit your needs, change the "World.getWorld().getMySQLHandler()" to wherever you created the instance of it.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement