1、JAVA客户端Jedis
Jedis:一款java 操作redis数据库的工具
使用步骤:
1、下载jedis相关的jar包
jedis.jar
commons-pool.jar
2、使用
2、jedis操作String
过期时间,激活码存储过期时间
3、jedis操作hash
4、jedis操作列表list
5、jedis操作set 和sortedset
package dayRedis;
import org.junit.*;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author duyanyan
* @date 2022/6/5 15:27
* Jedis的测试类
*/
public class JedisTest {
/*
快速入门
*/
@Test
public void test1(){
//获取连接
Jedis jedis = new Jedis("localhost",6379);
//操作
jedis.set("username","zhangsan");
//关闭连接
jedis.close();
}
@Test
public void test2(){
//获取连接
Jedis jedis = new Jedis("localhost",6379);
//操作
jedis.set("username","zhangsan");
String username = jedis.get("username");
System.out.println("string获取:" + username);
//将active ,hehe键值对存入redis.并且20s后自动删除该键值对
jedis.setex("active",20,"hehe");
//关闭连接
jedis.close();
System.out.println("-------------------------");
}
@Test
public void test3(){
//获取连接
Jedis jedis = new Jedis("localhost",6379);
//存储hash
jedis.hset("user","name","lisa");
jedis.hset("user","age","18");
jedis.hset("user","gender","male");
//获取hash
String name = jedis.hget("user", "name");
System.out.println("hash获取:" + name);
//获取hash的所有map中的集合
Map<String, String> user = jedis.hgetAll("user");
Set<String> strings = user.keySet();
for (String key : strings) {
//获取value
String value = user.get(key);
System.out.println(key + ":" + value);
}
//关闭连接
jedis.close();
System.out.println("-------------------------");
}
@Test
public void test4(){
//获取连接
Jedis jedis = new Jedis("localhost",6379);
//操作list
jedis.lpush("mylist","a","b","c"); //从左边存
jedis.rpush("mylist","a","b","c"); //从右边村
//获取范围
List<String> mylist = jedis.lrange("mylist", 0, -1);
System.out.println("list的输出:" + mylist);
//弹出
String mylist1 = jedis.lpop("mylist");
System.out.println("mylist从左边弹出的元素:" + mylist1);
String mylist2 = jedis.rpop("mylist");
System.out.println("mylist从右边弹出的元素:" + mylist2);
List<String> mylistall = jedis.lrange("mylist", 0, -1);
System.out.println("list最后的输出:" + mylistall);
//关闭连接
jedis.close();
}
}
输出:
string获取:zhangsan
-------------------------
hash获取:lisa
name:lisa
gender:male
age:18
-------------------------
list的输出:[c, b, a, a, b, c]
mylist从左边弹出的元素:c
mylist从右边弹出的元素:c
list最后的输出:[b, a, a, b]