最基础的数据同步就是将数据存储到 Redis 中,并在需要时读取出来。例如,你可以将用户的一些频繁访问的数据存储在 Redis 中,从而减少对后端数据库的压力。
import redis.clients.jedis.Jedis;
public class DataSyncExample {
private static final String REDIS_HOST = "localhost";
private static final int REDIS_PORT = 6379;
public static void main(String[] args) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
// 存储数据
String key = "exampleKey";
String value = "someValue";
String response = jedis.set(key, value);
System.out.println("Data stored: " + response);
// 读取数据
String data = jedis.get(key);
System.out.println("Data retrieved: " + data);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
为了保证数据的一致性,通常会在更新主存储的同时清除 Redis 中的缓存数据,或者采用读取时更新策略(read-through caching)。
public class CacheConsistencyExample {
public static void updateData(String key, String newValue) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
// 更新主存储中的数据(这里假定有一个方法 updateDatabase)
updateDatabase(key, newValue);
// 清除 Redis 中的旧数据
jedis.del(key);
// 重新加载数据到 Redis 中
jedis.set(key, newValue);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
使用 Redis 的 SETNX
或 SET
命令(带有 NX 和 PX 参数)来实现分布式锁,确保在高并发环境下数据的一致性。
public class DistributedLockExample {
public static boolean lock(String lockKey, long expireTimeMs) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
String identifier = UUID.randomUUID().toString();
Long result = jedis.setnx(lockKey, identifier);
if (result == 1L) { // 锁获取成功
jedis.expire(lockKey, (int) (expireTimeMs / 1000)); // 设置过期时间
return true;
}
return false;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static void unlock(String lockKey) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
jedis.del(lockKey);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
Redis 的发布/订阅功能允许程序间发送消息。这对于实时应用非常有用,比如通知系统。
import redis.clients.jedis.JedisPubSub;
public class PubSubExample {
public static void publishMessage(String channelName, String message) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
jedis.publish(channelName, message);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
public static void subscribeMessages(String channelName) {
Jedis jedis = new Jedis(REDIS_HOST, REDIS_PORT);
try {
jedis.subscribe(new JedisPubSub() {
@Override
public void onMessage(String channel, String message) {
System.out.println("Received message [" + message + "] from channel [" + channel + "]");
}
}, channelName);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
这些示例展示了如何在 Java 中利用 Redis 进行基本的数据同步。在实际应用中,可能还需要考虑更复杂的场景,如数据的持久化、集群支持等。