redis作为mysql缓冲登录查询判断种查询方式的速度
这里的数据库是用的mysql自带的world数据库
先上jdbc链接代码
···
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static java.lang.Class.*;
public class DBUtils {
static final String DB_URL = "jdbc:mysql://localhost:3306/world?useSSL=false&serverTimezone=UTC";
private static final String NAME="root";
private static final String PASSWORD="xxxxxxxx";
private static Connection conn=null;
private static String DRIVER = "com.mysql.cj.jdbc.Driver";
static {
try{
Class.forName(DRIVER);
conn= DriverManager.getConnection(DB_URL, NAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnetion(){
return conn;
}
}
···
···
import redis.clients.jedis.Jedis;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class Redis_MySql_test {
public void logintest() throws SQLException {
String key="eee";
Jedis redis = new Jedis("localhost");
String Name="Herat";
String sql="select * from world.city where Name='"+Name+"'";
String District;
Connection con=DBUtils.getConnetion();
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery(sql);
long startTime = System.currentTimeMillis();
if(redis.hexists(key,Name)){
long endTime = System.currentTimeMillis();
System.out.println("程序运行时间:" + (endTime - startTime) + "ms"); //输出程序运行时间y
District=redis.hget("Name"+Name, "DIstrict");
System.out.println("Welcome Redis! User "+District+" login success");
}else {
if(rs.next()==false){
System.out.println("不存在");
}else {
District=rs.getString("District");
System.out.println("Welcome Mysql ! User "+District+" login success");
redis.hset(key,Name,District);
//30分钟未操作就过期
redis.expire(key, 1800);
}
}
}
public static void main(String[] args) throws SQLException {
Redis_MySql_test r1=new Redis_MySql_test();
r1.logintest();
}
}
···