创建maven项目
引入依赖
<dependencies>
<!--Redis的依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.2.0</version>
</dependency>
<!--test的依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
注意事项
关闭Linux的防火墙
systemctl stop firewalld
禁用Linux的防火墙
systemctl disable firewalld
redis.conf中注释掉bind 127.0.0.1 ,然后 protected-mode no
Jedis操作
package com.xxxx.redis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Set;
/**
* Jedis操作
*
* @author : li.linnan
* @create : 2023/1/13
*/
public class Demo001 {
@Test
public void demo() {
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//测试
System.out.println("连接状态:"+jedis.ping());
}
@Test
public void stringDemo(){
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//清除数据
System.out.println("清除数据: "+jedis.flushDB());
//添加
System.out.println("添加数据: "+jedis.set("name","zhangsan"));
System.out.println("添加数据: "+jedis.mset("k1","v1","k2","v2"));
//输出
System.out.println("name: "+jedis.get("name"));
List<String> mget = jedis.mget("k1","k2");
System.out.println(mget);
//获取所有的key
Set<String> keys = jedis.keys("*");
//遍历输出
System.out.println("---------------------key");
keys.forEach(System.out::println);
System.out.println("---------------------key");
//keys数量
System.out.println(keys.size());
//是否存在
System.out.println(jedis.exists("k1"));
//key的有效时间
System.out.println(jedis.ttl("k1"));
//返回key的value
System.out.println(jedis.get("k1"));
}
@Test
public void listDemo(){
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//清除数据
System.out.println("清除数据: "+jedis.flushDB());
//添加
jedis.lpush("k1","a","b","c");
//获取
List<String> values = jedis.lrange("k1",0,-1);
//输出
System.out.println(values);
}
@Test
public void setDemo(){
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//清除数据
System.out.println("清除数据: "+jedis.flushDB());
//添加
jedis.sadd("k1","a","b","c","c");
//获取
Set<String> values = jedis.smembers("k1");
//输出
System.out.println(values);
}
@Test
public void hashDemo(){
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//清除数据
System.out.println("清除数据: "+jedis.flushDB());
//添加
jedis.hset("users","name","marry");
jedis.hset("users","age","20");
//获取
String value1 = jedis.hget("users","name");
List<String> value2 = jedis.hmget("users","name","age");
//输出
System.out.println(value1);
System.out.println(value2);
}
@Test
public void zsetDemo(){
//创建redis对象
Jedis jedis = new Jedis("192.168.10.130",6379);
//清除数据
System.out.println("清除数据: "+jedis.flushDB());
//添加
jedis.zadd("user",100,"shanxi");
//获取
Set<String> zrange = jedis.zrange("user",0,-1);
//输出
System.out.println(zrange);
zrange.forEach(System.out::println);
}
}