集成开发(暂以Java为例)
Java
底层实现 | 原生 Socket 直连 | Netty 异步非阻塞 | 封装了 Jedis 或 Lettuce |
线程安全 | ❌ 不安全(需连接池) | ✅ 安全(自带连接池) | ✅ 安全(由底层客户端决定) |
连接复用 | 需要手动管理连接池 | 自带连接池,支持复用 | 通过配置选择 Jedis/Lettuce |
API 设计 | 接口直接对应 Redis 命令 | 支持同步/异步/响应式编程 | 提供更高级别的抽象 API |
集成 Spring | 可以集成但不如 Spring Data Redis 简洁 | 可以集成但不如 Spring Data Redis 简洁 | ✅ 最推荐的 Spring 整合方式 |
适合场景 | 轻量级项目、学习用途 | 高并发、分布式系统 | Spring Boot 项目首选 |
Jedis
依赖载入
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<!-- <version>3.2.0</version> -->
</dependency>
基本用法
// 进行简单的redis操作
import com.alibaba.fastjson2.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
public class TestJedis {
public static void main(String[] args) {
try (Jedis jedis = new Jedis("localhost", 6379);) {
System.out.println(jedis.auth("123456"));
System.out.println(jedis.ping());
System.out.println(jedis.select(1));
System.out.println(jedis.dbSize());
String select = jedis.select(0);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "ssydx");
jsonObject.put("age", 25);
String jsonString = jsonObject.toJSONString();
Transaction multi = jedis.multi();
multi.set("name", "ssydx");
multi.set("age", "25");
multi.set("user", jsonString);
multi.exec();
String name = jedis.get("name");
String age = jedis.get("age");
String user = jedis.get("user");
System.out.println(name);
System.out.println(age);
System.out.println(user);
jedis.flushDB();
jedis.quit();
}
}
}
Lettuce
采用netty,线程安全,自带连接池,天生支持连接复用
依赖载入
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
<!-- <version>5.2.2.RELEASE</version> -->
</dependency>
基本用法
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class TestLettuce {
public static void main(String[] args) {
// 构建带认证信息的 URI
RedisURI redisURI = RedisURI.Builder.redis("localhost", 6379)
.withPassword("123456".toCharArray())
.build();
// 创建Redis客户端
RedisClient redisClient = RedisClient.create(redisURI);
// 获取连接
StatefulRedisConnection<String, String> connection = redisClient.connect();
// 获取同步命令
RedisCommands<String, String> syncCommands = connection.sync();
// 执行一些命令
syncCommands.set("key", "Hello, Redis!");
System.out.println(syncCommands.get("key"));
// 关闭连接
connection.close();
// 关闭客户端
redisClient.shutdown();
}
}
Spring Data Redis
载入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<!-- <version>3.4.5</version> -->
</dependency>
配置类
// 如果不进行自定义RedisTemplate,对象存储会采用Java序列化机制,POJO类必须实现IMPLEMENT接口
// Java序列化机制还会造成数据库乱码(不可直接阅读),因此推荐使用JSON序列化机制
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
// 配置序列化器
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
return template;
}
}
POJO类
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
// 由于使用了Jackson的序列化,此处不序列化也行
public class User implements Serializable {
private String name;
private Integer age;
}
基本用法
// 仅作为演示,实际通常会包装一个redis工具类,而不是直接使用template
import java.util.Properties;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
@SpringBootTest
public class TestRedis {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
void test() {
System.out.println("RedisTemplate: " + stringRedisTemplate);
String requirepasswd = stringRedisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
Properties config = connection.getConfig("requirepass");
return config.getProperty("requirepass");
}
});
System.out.println(requirepasswd);
stringRedisTemplate.opsForValue().set("name", "ssydx");
stringRedisTemplate.opsForList().leftPush("ls", "ssydx");
stringRedisTemplate.opsForSet().add("set", "ssydx");
stringRedisTemplate.opsForHash().put("hash", "name", "ssydx");
stringRedisTemplate.opsForZSet().add("zset", "ssydx", 1);
Set<String> keys = stringRedisTemplate.keys("*");
System.out.println(keys);
stringRedisTemplate.execute(new RedisCallback<Void>() {
@Override
public Void doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return null;
}
});
User user = new User("ssydx", 25);
redisTemplate.opsForValue().set("user", user);
System.out.println(redisTemplate.opsForValue().get("user"));
redisTemplate.delete("user");
}
}
#redis#Redis 文章被收录于专栏
此专栏由于更新观看不便,不会保持及时更新,最新更新见计算机合集专栏https://www.nowcoder.com/creation/manager/columnDetail/04yp33