Redis缓存详解:Java Redis客户端
Redis缓存详解:Java Redis客户端
概述
Redis是高性能的内存数据库。本教程介绍Java中Redis客户端的使用。
1. Jedis
import redis.clients.jedis.Jedis;
public class JedisExample {
public static void main(String[] args) {
try (Jedis jedis = new Jedis("localhost", 6379)) {
// 字符串操作
jedis.set("name", "Alice");
String name = jedis.get("name");
System.out.println("name: " + name);
// 哈希操作
jedis.hset("user:1", "name", "Bob");
jedis.hset("user:1", "age", "30");
System.out.println("user:1: " + jedis.hgetAll("user:1"));
// 列表操作
jedis.lpush("list", "a", "b", "c");
System.out.println("list: " + jedis.lrange("list", 0, -1));
// 集合操作
jedis.sadd("set", "x", "y", "z");
System.out.println("set: " + jedis.smembers("set"));
// 有序集合
jedis.zadd("sorted", 1.0, "a");
jedis.zadd("sorted", 2.0, "b");
System.out.println("sorted: " + jedis.zrangeWithScores("sorted", 0, -1));
}
}
}
2. Lettuce
import io.lettuce.core.*;
import io.lettuce.core.api.StatefulRedisConnection;
import java.time.Duration;
public class LettuceExample {
public static void main(String[] args) {
RedisClient client = RedisClient.create("redis://localhost:6379");
try (StatefulRedisConnection<String, String> connection = client.connect()) {
RedisCommands<String, String> commands = connection.sync();
// 字符串操作
commands.set("name", "Alice");
String name = commands.get("name");
System.out.println("name: " + name);
// 设置过期时间
commands.setex("temp", 60, "value");
// 哈希操作
commands.hset("user:1", "name", "Bob");
System.out.println("user:1: " + commands.hgetall("user:1"));
// 发布订阅
RedisPubSubCommands<String, String> pubSub = connection.sync();
}
client.shutdown();
}
}
3. Spring RedisTemplate
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class RedisService {
private final RedisTemplate<String, Object> redisTemplate;
public RedisService(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public void set(String key, Object value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public Boolean delete(String key) {
return redisTemplate.delete(key);
}
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
public void increment(String key, long delta) {
redisTemplate.opsForValue().increment(key, delta);
}
}
4. 实际应用示例
分布式锁
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit;
public class DistributedLock {
private final RedisTemplate<String, String> redisTemplate;
private final String lockKey;
private final long lockTimeout;
public DistributedLock(RedisTemplate<String, String> redisTemplate,
String lockKey, long lockTimeout) {
this.redisTemplate = redisTemplate;
this.lockKey = lockKey;
this.lockTimeout = lockTimeout;
}
public boolean tryLock() {
return Boolean.TRUE.equals(
redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", lockTimeout, TimeUnit.MILLISECONDS)
);
}
public void unlock() {
redisTemplate.delete(lockKey);
}
}
缓存管理
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
@Service
@CacheConfig(cacheNames = "users")
public class UserService {
@Cacheable(key = "#id")
public User findById(Long id) {
// 从数据库查询
return userRepository.findById(id).orElse(null);
}
@CachePut(key = "#user.id")
public User save(User user) {
return userRepository.save(user);
}
@CacheEvict(key = "#id")
public void deleteById(Long id) {
userRepository.deleteById(id);
}
}
5. 最佳实践
- 选择合适的客户端:Jedis简单,Lettuce功能丰富
- 使用连接池:提高性能
- 设置过期时间:避免内存溢出
- 使用Pipeline:批量操作提高性能
- 监控Redis状态:使用Redis INFO命令
总结
Redis是高性能的内存数据库。掌握Java Redis客户端的使用,可以实现缓存、分布式锁等功能,提高应用性能。