Java uses Redis
Installation
Before you start using Redis in Java, We need to ensure that the redis service and Java redis driver have been installed, and Java can be used normally on your machine. For Java installation configuration, please refer to our Java development environment configuration. Next, let us install the Java redis driver:
First you need to download the driver package, Download jedis.jar , make sure to download the latest driver package.
Include the driver package in your classpath.
Connect to the redis service
import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //查看服务是否运行 System.out.println("Server is running: "+jedis.ping()); } }
Compile the above Java program and make sure the path to the driver package is correct.
$javac RedisJava.java $java RedisJava Connection to server sucessfully Server is running: PONG Redis Java String Example
Redis Java String (string) Example
import redis.clients.jedis.Jedis; public class RedisStringJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //设置 redis 字符串数据 jedis.set("w3ckey", "Redis tutorial"); // 获取存储的数据并输出 System.out.println("Stored string in redis:: "+ jedis.get("w3ckey")); } }
Compile the above program.
$javac RedisStringJava.java $java RedisStringJava Connection to server sucessfully Stored string in redis:: Redis tutorial
Redis Java List (list) Example
import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //存储数据到列表中 jedis.lpush("tutorial-list", "Redis"); jedis.lpush("tutorial-list", "Mongodb"); jedis.lpush("tutorial-list", "Mysql"); // 获取存储的数据并输出 List<String> list = jedis.lrange("tutorial-list", 0 ,5); for(int i=0; i<list.size(); i++) { System.out.println("Stored string in redis:: "+list.get(i)); } } }
Compile the above program.
$javac RedisListJava.java $java RedisListJava Connection to server sucessfully Stored string in redis:: Redis Stored string in redis:: Mongodb Stored string in redis:: Mysql
Redis Java Keys Example
import redis.clients.jedis.Jedis; public class RedisKeyJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); // 获取数据并输出 List<String> list = jedis.keys("*"); for(int i=0; i<list.size(); i++) { System.out.println("List of stored keys:: "+list.get(i)); } } }
Compile the above program.
$javac RedisKeyJava.java $java RedisKeyJava Connection to server sucessfully List of stored keys:: tutorial-name List of stored keys:: tutorial-list