以下是使用Java实现从数据库查出数据存入Redis,并在查询时先查Redis,如果Redis中没有数据再从数据库中读取的示例代码:
首先,确保已经引入了Redis的Java客户端依赖,例如Jedis:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
接下来,我们需要创建一个RedisUtil类,用于连接Redis并提供操作方法:
import redis.clients.jedis.Jedis;
public class RedisUtil {
private static final String REDIS_HOST = "localhost";
private static final int REDIS_PORT = 6379;
private static Jedis jedis;
public static Jedis getJedis() {
if (jedis == null) {
jedis = new Jedis(REDIS_HOST, REDIS_PORT);
}
return jedis;
}
public static void set(String key, String value) {
getJedis().set(key, value);
}
public static String get(String key) {
return getJedis().get(key);
}
public static void close() {
if (jedis != null) {
jedis.close();
}
}
}
然后,我们需要创建一个Dao类,用于从数据库中读取数据,并将数据存入Redis:
import java.sql.*;
public class DataDao {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "password";
public static String getDataFromDatabase(String key) {
String data = RedisUtil.get(key);
if (data == null) {
data = fetchDataFromDatabase(key);
if (data != null) {
RedisUtil.set(key, data);
}
}
return data;
}
private static String fetchDataFromDatabase(String key) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String data = null;
try {
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT data FROM mytable WHERE key = '" + key + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
data = rs.getString("data");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return data;
}
}
最后,我们可以在主程序中调用Dao类的方法进行测试:
public class Main {
public static void main(String[] args) {
String key = "mykey";
String data = DataDao.getDataFromDatabase(key);
System.out.println(data);
RedisUtil.close();
}
}
在上述示例中,我们首先尝试从Redis中获取数据,如果获取失败,则从数据库中查询数据,并将查询到的数据存入Redis中,以便下次查询时直接从Redis中获取数据。在关闭程序之前,需要调用RedisUtil.close()
方法关闭Redis连接。
请根据实际情况修改示例中的数据库连接信息和查询语句来适配您的应用场景。