Jedis操作Redis
Jedis使用的基本步骤:
- 1.引入依赖
- 2.Jedis连接池配置
- 3.创建Jedis对象,建立连接
- 4.使用Jedis,方法名与Redis命令一致
- 5.释放资源
1.引入依赖
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
2.Jedis连接池配置:
package com.starQeem.jedis.utils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisConnectionFactory {
private static final JedisPool jedisPool;
static {
//配置连接池
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(8);
poolConfig.setMaxIdle(8);
poolConfig.setMinIdle(0);
poolConfig.setMaxWaitMillis(1000);
//创建连接池对象
jedisPool = new JedisPool(poolConfig,"106.53.103.231",6379,1000,"1234");
}
public static Jedis getJedis(){
return jedisPool.getResource();
}
}
- 3.创建Jedis对象,建立连接:
private Jedis jedis;
@BeforeEach
void setUp() {
//建立连接
// jedis = new Jedis("106.53.103.231", 6379);
jedis = JedisConnectionFactory.getJedis();
//设置密码
jedis.auth("1234");
//选择库
jedis.select(0);
}
- 4.使用Jedis,方法名与Redis命令一致:
//测试String
@Test
void testString() {
//插入数据,方法名就是redis命令名称
String result = jedis.set("name", "张三");
System.out.println("result:" + result);
//获取资源
String name = jedis.get("name");
System.out.println(name);
}
//测试hash
@Test
void testHash() {
//插入数据
jedis.hset("user:5", "name", "Qeem");
jedis.hset("user:5", "age", "18");
//获取资源
System.out.println(jedis.hget("user:5", "name"));
System.out.println(jedis.hget("user:5", "age"));
System.out.println(jedis.hgetAll("user:5"));
}
//测试list
@Test
void testList() {
//插入数据
jedis.lpush("star", "1", "2", "3", "4", "5");
//获取资源
System.out.println(jedis.lrange("star", 0, 5));
}
//测试set
@Test
void testSet() {
//插入数据
jedis.sadd("starQeem", "1", "2", "3", "4");
//获取资源
System.out.println(jedis.smembers("starQeem"));
}
//测试sorted set
@Test
void testSortedSet() {
//插入数据
jedis.zadd("starQeem2", 88, "星星");
jedis.zadd("starQeem2", 99, "Qeem");
jedis.zadd("starQeem2", 10, "pig");
//获取资源
System.out.println(jedis.zscore("starQeem2", "星星"));
System.out.println(jedis.zscore("starQeem2", "Qeem"));
System.out.println(jedis.zscore("starQeem2", "pig"));
}
- 5.释放资源:
//释放资源
@AfterEach
void tearDown() {
if (jedis != null) {
jedis.close();
}
}
评论区