Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.09 KB | None | 0 0
  1. 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.
  2.  
  3. Features:
  4. Creates connections on-demand (Not the best for remote connections, which noone SHOULD be using anyways)
  5. Cleans up inactive connections
  6. Executes in a multi-thread environment for longer queries
  7. Multiple database support
  8. Easy to use settings
  9.  
  10. Spoiler for Code:
  11.  
  12. MySQL.java
  13. (Note: The stale connection time should not be changed unless it is still picking up stale connections, in that case, try 30000ms)
  14.  
  15. Code:
  16. package org.hyperion.rs2.net.mysql;
  17.  
  18. import java.util.concurrent.ExecutorService;
  19. import java.util.concurrent.Executors;
  20.  
  21. /**
  22. *
  23. * @author Nicole <nicole@rune-server.org>
  24. *
  25. * @version 1.0
  26. *
  27. */
  28.  
  29. public class MySQL {
  30.  
  31. public static final String HOST = "localhost";
  32. public static final String USERNAME = "username";
  33. public static final String PASSWORD = "password";
  34. public static final String[] DATABASES = {"database"};
  35.  
  36. public static final String HOST_BASE = "jdbc:mysql://";
  37.  
  38. public static final int MAX_CONNECTIONS = 5; //More for higher query counts
  39. public static final int THREAD_COUNT = 1; //Change this to suit your needs
  40. public static final int STALE_CONNECTION = 60000;
  41. public static final String DRIVER = "org.gjt.mm.mysql.Driver";
  42.  
  43. private ExecutorService workerService = Executors.newFixedThreadPool(THREAD_COUNT);
  44.  
  45. private MySQLConnectionPool[] pools;
  46.  
  47. public MySQL() {
  48. try {
  49. Class.forName(DRIVER);
  50. } catch (ClassNotFoundException e) {
  51. e.printStackTrace();
  52. }
  53. pools = new MySQLConnectionPool[DATABASES.length];
  54. for(int i = 0; i < DATABASES.length; i++) {
  55. pools[i] = new MySQLConnectionPool(MAX_CONNECTIONS);
  56. pools[i].addDetail("url", parseURL(DATABASES[i]))
  57. .addDetail("user", USERNAME)
  58. .addDetail("password", PASSWORD);
  59. }
  60. }
  61.  
  62. public void cleanup() {
  63. for(MySQLConnectionPool pool : getPools()) {
  64. pool.cleanConnections();
  65. }
  66. }
  67.  
  68. public MySQLConnectionPool getPool(int index) {
  69. return pools[index];
  70. }
  71.  
  72. public MySQLConnectionPool[] getPools() {
  73. return pools;
  74. }
  75.  
  76. public ExecutorService getWorker() {
  77. return workerService;
  78. }
  79.  
  80. public String parseURL(String database) {
  81. StringBuilder builder = new StringBuilder();
  82. builder.append(HOST_BASE);
  83. builder.append(HOST);
  84. builder.append("/");
  85. builder.append(database);
  86. return builder.toString();
  87. }
  88.  
  89. public void shutdown() {
  90. for(int i = 0; i < pools.length; i++) {
  91. for(int il = 0; il < pools[i].getPool().size(); il++) {
  92. try {
  93. pools[i].getPool().get(il).getConnection().close();
  94. } catch(Exception e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. }
  99. }
  100. }
  101. MySQLConnectionPool.java
  102.  
  103. Code:
  104. package org.hyperion.rs2.net.mysql;
  105.  
  106. import java.sql.DriverManager;
  107. import java.sql.SQLException;
  108. import java.util.ArrayList;
  109. import java.util.HashMap;
  110. import java.util.Iterator;
  111.  
  112. /**
  113. *
  114. * @author Nicole <nicole@rune-server.org>
  115. *
  116. * @version 1.0
  117. *
  118. */
  119.  
  120. public class MySQLConnectionPool {
  121.  
  122. private HashMap<String, String> details = new HashMap<String, String>();
  123.  
  124. private ArrayList<PoolConnection> pool;
  125.  
  126. public MySQLConnectionPool(int numconn) {
  127. pool = new ArrayList<PoolConnection>(numconn);
  128. }
  129.  
  130. public MySQLConnectionPool addDetail(String key, String value) {
  131. details.put(key, value);
  132. return this;
  133. }
  134.  
  135. public void cleanConnections() {
  136. Iterator<PoolConnection> it$ = pool.iterator();
  137. long time = System.currentTimeMillis();
  138. while(it$.hasNext()) {
  139. PoolConnection c = it$.next();
  140. try {
  141. if(time - c.getLastUse() >= MySQL.STALE_CONNECTION
  142. || c.getConnection().isClosed()) {
  143. if(!c.getConnection().isClosed()) {
  144. c.getConnection().close();
  145. }
  146. it$.remove();
  147. }
  148. } catch(Exception e) {
  149. e.printStackTrace();
  150. }
  151. }
  152. }
  153.  
  154. public PoolConnection getFreeConnection() {
  155. PoolConnection c;
  156. for(int i = 0; i < pool.size(); i++) {
  157. c = pool.get(i);
  158. if(c.borrow()) {
  159. return c;
  160. }
  161. }
  162. c = new PoolConnection();
  163. try {
  164. c.setConnection(DriverManager.getConnection(details.get("url"),
  165. details.get("user"), details.get("password")));
  166. } catch (SQLException e) {
  167. e.printStackTrace();
  168. }
  169. c.borrow();
  170. pool.add(c);
  171. return c;
  172. }
  173.  
  174. public ArrayList<PoolConnection> getPool() {
  175. return pool;
  176. }
  177. }
  178. PoolConnection.java
  179.  
  180. Code:
  181. package org.hyperion.rs2.net.mysql;
  182.  
  183. import java.sql.Connection;
  184. import java.sql.SQLException;
  185.  
  186. /**
  187. *
  188. * @author Nicole <nicole@rune-server.org>
  189. *
  190. * @version 1.0
  191. *
  192. */
  193.  
  194. public class PoolConnection {
  195.  
  196. private Connection connection;
  197.  
  198. private boolean inUse = false;
  199.  
  200. private long lastUse = System.currentTimeMillis();
  201.  
  202. public PoolConnection() {
  203. }
  204.  
  205. public boolean borrow() {
  206. try {
  207. boolean inuse = (!inUse && !connection.isClosed());
  208. if(!inuse) {
  209. setUsed(true);
  210. }
  211. return inuse;
  212. } catch (SQLException e) {
  213. e.printStackTrace();
  214. }
  215. return false;
  216. }
  217.  
  218. public Connection getConnection() {
  219. return connection;
  220. }
  221.  
  222. public long getLastUse() {
  223. return lastUse;
  224. }
  225.  
  226. public boolean isInUse() {
  227. return inUse;
  228. }
  229.  
  230. public void release() {
  231. setUsed(false);
  232. }
  233.  
  234. public PoolConnection setConnection(Connection connection) {
  235. this.connection = connection;
  236. return this;
  237. }
  238.  
  239. public void setUsed(boolean bool) {
  240. inUse = bool;
  241. if(!bool) {
  242. lastUse = System.currentTimeMillis();
  243. }
  244. }
  245. }
  246. MySQLResultCallable.java
  247.  
  248. Code:
  249. package org.hyperion.rs2.net.mysql;
  250.  
  251. import java.sql.ResultSet;
  252. import java.sql.Statement;
  253. import java.util.concurrent.Callable;
  254.  
  255. import org.hyperion.rs2.model.World;
  256.  
  257. /**
  258. *
  259. * @author Nicole <nicole@rune-server.org>
  260. *
  261. * @version 1.0
  262. *
  263. */
  264.  
  265. public class MySQLResultCallable implements Callable<ResultSet> {
  266.  
  267. private String query;
  268. private int pool;
  269.  
  270. public MySQLResultCallable(int pool, String query) {
  271. this.query = query;
  272. this.pool = pool;
  273. }
  274.  
  275. @Override
  276. public ResultSet call() throws Exception {
  277. PoolConnection connection = World.getWorld().getMySQLHandler().getPool(pool).getFreeConnection();
  278. if(connection == null)
  279. throw new Exception("Unable to use/create a MySQL connection, Please make sure the MySQL server is running and accepting connections.");
  280. Statement stmt = connection.getConnection().createStatement();
  281. stmt.execute(query);
  282. connection.release();
  283. return stmt.getResultSet();
  284. }
  285. }
  286.  
  287.  
  288. Usage:
  289.  
  290. 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.
  291.  
  292. Inserting:
  293.  
  294. Code:
  295. try {
  296. MySQLResultCallable query = new MySQLResultCallable(0, "INSERT INTO database VALUES('hi', 'hi there :P')");
  297. Future<ResultSet> future = World.getWorld().getMySQLHandler().getWorker().submit(query);
  298. future.get(); //Result set doesn't need to be closed, because we are not selecting anything.
  299. } catch (Exception e) {
  300. e.printStackTrace();
  301. }
  302. Selecting:
  303.  
  304. Code:
  305. try {
  306. MySQLResultCallable query = new MySQLResultCallable(0, "SELECT * FROM database");
  307. Future<ResultSet> future = World.getWorld().getMySQLHandler().getWorker().submit(query);
  308. ResultSet rs = future.get();
  309. while (rs.next()) {
  310. String somefield = rs.getString("label"); //column label
  311. String somefield2 = rs.getString(0); //column index
  312. int somefield3 = rs.getInt("label"); //column label
  313. int somefield4 = rs.getInt(0); //column index
  314. //Do whatever with the data
  315. }
  316. rs.close(); //MAKE SURE to close the result set to free up memory
  317. } catch(Exception e) {
  318. e.printStackTrace();
  319. }
  320. Cleaning up connections:
  321.  
  322. Code:
  323. new Thread(new Runnable() {
  324. public void run() {
  325. while(true) {
  326. World.getWorld().getMySQLHandler().cleanup();
  327. try {
  328. Thread.sleep(1000);
  329. } catch(Exception e) {
  330. break;
  331. }
  332. }
  333. }
  334. }).start();
  335.  
  336. 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