1.先建立连接,连接上mysql跟redis
2.读取mysql中的数据表
3,将读取的数据set到redis中
代码片段:` //连接本地的Redis服务
Jedis jedis = new Jedis(“redis的ip”, 6379);
System.out.println(“连接成功!”);
//密码验证
jedis.auth(“aaa”);
//查看服务是否运行
System.out.println(“服务是否运行:” + jedis.ping());
//数据库连接名称
String username="root";
//数据库连接密码
String password="123";
String driver="com.mysql.jdbc.Driver";
//其中test为数据库名称
String url="jdbc:mysql://127.0.0.1/test2";
Connection conn=null;
Class.forName(driver);
conn=(Connection) DriverManager.getConnection(url,username,password);
String sql = "SELECT * FROM table1";
Statement createStatement = conn.createStatement();
ResultSet rs = createStatement.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int num = md.getColumnCount();
while (rs.next()) {
JSONObject mapOfColValues = new JSONObject();
for (int i = 1; i <= num; i++) {
try {
mapOfColValues.put(md.getColumnName(i), rs.getObject(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
jedis.sadd("table1", mapOfColValues.toString());
System.out.println(mapOfColValues.toString());
}`
之后运行代码,在redis的客户端中可以看到数据导入