Jedis 客户端
Jedis 基于 Java 实现,是 shell 程序连接 Redis 数据库最常使用的工具。提供了比较全面的 Redis 命令的支持。
导入依赖
Spring Boot 2.x 版本 Redis 默认导入了 lettuce,需要排除才能使用 Redis .
<!-- Redis --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions></dependency><!-- Jedis --><dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId></dependency>Copy to clipboardErrorCopied
复制代码
基本使用
使用引入的 Jedis 类即可连接 Redis 数据库并进行操作。操作名取自 Redis 指令,如果出现问题则会抛出 JedisDataException。
import redis.clients.jedis.Jedis;
public class JedisTest{ @Test public void jedisTest (){ // 连接 Redis Jedis jedis = new Jedis("127.0.0.1", 6379); // 对 Redis 操作(直接使用 Redis 指令) try { jedis.set("name", "MrJoker"); System.out.print(jedis.get("name")); } catch(JedisDataException e) { System.out.print("error"); } finally { // 关闭 Redis 连接 jedis.close(); } }}Copy to clipboardErrorCopied
复制代码
在实际开发中,创建多个 Redis 连接会非常复杂且难以管理,Jedis 提供了 JedisPool 类作为 Redis 连接池来管理 Redis 连接。
import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;
public class JedisTest{ @Test public void jedisTest (){ // 配置连接池 JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(50); // 最大空闲数 poolConfig.setMaxTotal(100); // 最大连接数 poolConfig.setMaxWaitMillis(20000); // 最大等待毫秒数 // 创建连接池 JedisPool pool = new JedisPool(poolConfig, "localhost"); // 从连接池中获取单个连接 Jedis jedis = pool.getResource(); // 如果需要密码 //jedis.auth("password"); }}Copy to clipboardErrorCopied
复制代码
Spring Boot 集成
Spring Boot 中,我们无需自行创建 Redis 连接,只需要在配置文件中配置好参数。
# REDIS配置# Redis数据库索引(默认为0)spring.redis.database=0# Redis服务器地址spring.redis.host=localhost# Redis服务器连接端口spring.redis.port=6379# Redis服务器连接密码(默认为空)spring.redis.password=# 连接池最大连接数(使用负值表示没有限制)spring.redis.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.pool.max-wait=-1# 连接池中的最大空闲连接spring.redis.pool.max-idle=8# 连接池中的最小空闲连接spring.redis.pool.min-idle=0# 连接超时时间(毫秒)spring.redis.timeout=0Copy to clipboardErrorCopied
复制代码
Spring Boot 提供默认的 RedisTemplate 工具类根据配置文件自动连接 Redis,自动加载后可以直接调用其中的方法去操作。
@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest()public class ApplicationTests {
@Autowired private RedisTemplate redisTemplate;
@Test public void test() throws Exception { User user = new User(); user.setName("我没有三颗心脏"); user.setAge(21); // 调用工具类方法 redisTemplate.opsForValue().set("user_1", user); User user1 = (User) redisTemplate.opsForValue().get("user_1"); System.out.println(user1.getName()); }}Copy to clipboardErrorCopied
复制代码
RedisTemplate 类常用操作
redisTemplate.delete(key); // 删除 keyredisTemplate.delete(keys); // 批量删除 keyredisTemplate.expire(key,time,TimeUnit.MINUTES); // 设置 key 失效时间Long expire = redisTemplate.getExpire(key); // 获取 key 失效时间Copy to clipboardErrorCopied
复制代码
Lettuce 客户端
更加高级的 Redis 客户端,用于线程安全同步,异步和响应使用,支持集群,Sentinel,管道和编码器。
导入依赖
在 spring boot 2.x 版本,为 Redis 默认导入了 Lettuce 。
<!-- Redis 默认导入 Lettuce --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>Copy to clipboardErrorCopied
复制代码
如果 Spring Boot 版本过低,也可以自行导入 Lettuce. Redis 版本至少需要 2.6 .
<!-- 单独导入 Lettuce --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>5.1.8.RELEASE</version></dependency>Copy to clipboardErrorCopied
复制代码
基本使用
public class LettuceTest { @Test public void testSetGet() throws Exception { // 注册连接信息 RedisURI redisUri = RedisURI.builder() .withHost("localhost") .withPort(6379) .withTimeout(Duration.of(10, ChronoUnit.SECONDS)) .build(); // 创建 Redis 客户端 RedisClient redisClient = RedisClient.create(redisUri); // 创建连接 StatefulRedisConnection<String, String> connection = redisClient.connect(); // 创建同步命令 RedisCommands<String, String> redisCommands = connection.sync(); SetArgs setArgs = SetArgs.Builder.nx().ex(5); String result = redisCommands.set("name", "throwable", setArgs); Assertions.assertThat(result).isEqualToIgnoringCase("OK"); result = redisCommands.get("name"); Assertions.assertThat(result).isEqualTo("throwable"); /******************** 其他操作 **********************/ connection.close(); // 关闭连接 redisClient.shutdown(); // 关闭客户端 }}Copy to clipboardErrorCopied
复制代码
Lettuce 主要提供三种 API:同步(sync)RedisCommands、异步(async)RedisAsyncCommands、反应式(reactive)RedisReactiveCommands。
Spring Boot 集成
同样在配置文件中配置好参数。
spring.redis.host=localhostspring.redis.port=6379spring.redis.password=root# 连接池最大连接数(使用负值表示没有限制) 默认为8spring.redis.lettuce.pool.max-active=8# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认为-1spring.redis.lettuce.pool.max-wait=-1ms# 连接池中的最大空闲连接 默认为8spring.redis.lettuce.pool.max-idle=8# 连接池中的最小空闲连接 默认为 0spring.redis.lettuce.pool.min-idle=0Copy to clipboardErrorCopied
复制代码
我们同样可以使用 Spring Boot 提供默认的 RedisTemplate 工具类根据配置文件自动连接 Redis。但默认情况下的模板只支持 RedisTemplate<String,String> 存入字符串,因此我们往往需要自定义 RedisTemplate 设置序列化器,以方便操作实例对象。
@Configurationpublic class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>(); // key 采用 String 的序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); // value 采用 jackson 的序列化方式 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // hash 采用 String/jackson 的序列化方式 redisTemplate.setHashKeySerializer(stringRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate; }}Copy to clipboardErrorCopied
复制代码
完成后即可用自定义的 RedisTemplate 工具类对 Redis 进行操作。
@RunWith(SpringRunner.class)@SpringBootTestpublic class RedisTest {
@Autowired private RedisTemplate<String, Serializable> redisTemplate;
@Test public void test() { String key = "user:1"; redisTemplate.opsForValue().set(key, new User(1,"pjmike",20)); User user = (User) redisTemplate.opsForValue().get(key); }}
复制代码
评论