May 16, 2021 Redis
Before we start using Redis in Java, we need to make sure that the redis service and Java redis driver are installed and that Java is working properly on your machine. J ava's installation configuration can refer to our Java development environment configuration Let's install the Java redis driver:
import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("连接成功"); //查看服务是否运行 System.out.println("服务器正在运行: "+jedis.ping()); } }
Compile the Java program above to make sure that the drive package has the correct path.
连接成功
服务正在运行:PONG
import redis.clients.jedis.Jedis;
public class RedisStringJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("连接成功"); //设置 redis 字符串数据 jedis.set("w3ckey", "www.w3cschool.cn"); // 获取存储的数据并输出 System.out.println("redis 存储的字符串为: "+ jedis.get("w3ckey")); } }
Compile the above program.
连接成功
redis 存储的字符串为:www.w3cschool.cn
import java.util.List
import redis.clients.jedis.Jedis;
public class RedisListJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("连接成功"); //存储数据到列表中 jedis.lpush("tutorial-list", "Redis"); jedis.lpush("tutorial-list", "Mongodb"); jedis.lpush("tutorial-list", "Mysql"); // 获取存储的数据并输出 List<String> list = jedis.lrange("tutorial-list", 0 ,2); for(int i=0; i<list.size(); i++) {
System.out.println("列表项为: "+list.get(i));
}
}
}
Compile the above program.
连接成功 列表项为: Redis 列表项为: Mongodb 列表项为: Mysql
import java.util.Iterator;
import java.util.Set;
import redis.clients.jedis.Jedis;
public class RedisKeyJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("连接成功"); // 获取数据并输出 Set<String> keys= jedis.keys("*");
Iterator<String> it=keys.iterator();
while(it.hasNext) {
String key=it.next();
System.out.println("key");
}
}
}
Compile the above program.
连接成功
w3ckey
tutorial-list