前言:事先說明:在實際應用中這種做法設計需要各位讀者自己設計,本文只提供一種思想。准備工作:安裝後本地數redis服務器,使用mysql數據庫,事先插入1000萬條數據,可以參考我之前的文章插入數據,這裡不再細說。我大概的做法是這樣的,編碼使用多線程訪問我的數據庫,在訪問數據庫前先訪問redis緩存沒有的話在去查詢數據庫,需要注意的是redis最大連接數最好設置為300,不然會出現很多報錯。
貼一下代碼吧
package select;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class SelectFromMysql {
public static void main(String[] args) {
JedisPool pool;
JedisPoolConfig config = new JedisPoolConfig();//創建redis連接池
// 設置最大連接數,-1無限制
config.setMaxTotal(300);
// 設置最大空閒連接
config.setMaxIdle(100);
// 設置最大阻塞時間,記住是毫秒數milliseconds
config.setMaxWaitMillis(100000);
// 創建連接池
pool = new JedisPool(config, "127.0.0.1", 6379,200000);
for (int i =9222000; i <=9222200; i++) {//這裡自己設置用多少線程並發訪問
String teacherName=String.valueOf(i);
new ThreadToMysql(teacherName, "123456",pool).start();
}
}
}
package select;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class ThreadToMysql extends Thread {
public String teacherName;
public String password;
public JedisPool pool;
public ThreadToMysql(String teacherName, String password,JedisPool pool) {//構造函數傳入要查詢登錄的老師姓名和密碼
this.teacherName=teacherName;
this.password=password;
this.pool=pool;
}
public void run() {
Jedis jedis = pool.getResource();
Long startTime=System.currentTimeMillis();//開始時間
if (jedis.get(teacherName)!=null) {
Long entTime=System.currentTimeMillis();//開始時間
System.out.println(currentThread().getName()+" 緩存得到的結果: "+jedis.get(teacherName)+" 開始時間:"+startTime+" 結束時間:"+entTime+" 用時:" +(entTime-startTime)+"ms");
pool.returnResource(jedis);
System.out.println("釋放該redis連接");
} else {
String url = "jdbc:mysql://127.0.0.1/teacher";
String name = "com.mysql.jdbc.Driver";
String user = "root";
String password = "123456";
Connection conn = null;
try {
Class.forName(name);
conn = DriverManager.getConnection(url, user, password);//獲取連接
conn.setAutoCommit(false);//關閉自動提交,不然conn.commit()運行到這句會報錯
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
if (conn!=null) {
String sql="select t_name from test_teacher where t_name='"+teacherName+"' and t_password='"+password+"' ";//SQL語句
String t_name=null;
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);//獲取結果集
if (rs.next()) {
t_name=rs.getString("t_name");
jedis.set(teacherName, t_name);
System.out.println("釋放該連接");
}
conn.commit();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
pool.returnResource(jedis);
System.out.println("釋放該連接");
}
Long end=System.currentTimeMillis();
System.out.println(currentThread().getName()+" 數據庫得到的查詢結果:"+t_name+" 開始時間:"+startTime+" 結束時間:"+end+" 用時:"+(end-startTime)+"ms");
} else {
System.out.println(currentThread().getName()+"數據庫連接失敗:");
}
}
}
}
我的數據庫表數據是這樣的。可以看到我的t_name是1-10000000,密碼固定123456.利用循環創建線程很好做傳入循環的次數作為查詢的t_name就行了
