Using Redis in Java

Installation

Before using Redis in Java, we need to ensure that the Redis service and the Java Redis driver are installed, and that Java works properly on your machine. For Java installation and configuration, you can refer to ourJava Development Environment ConfigurationNext, let's 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.

This site provides a 2.9.0 jar version download:jedis-2.9.0.jar


Connect to Redis service

Example

import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //Connect to local Redis service Jedis jedis = new Jedis("localhost"); //If the Redis service has a password set, the following line is needed; if not, it is not needed. // jedis.auth("123456"); System.out.println("Connected successfully"); //Check whether the service is running System.out.println("The service is running:"+jedis.ping()); } }

Compile the above Java program, making sure the path of the driver package is correct.

连接成功
服务正在运行: PONG

Redis Java String Example

Example

import redis.clients.jedis.Jedis; public class RedisStringJava { public static void main(String[] args) { //Connect to local Redis service Jedis jedis = new Jedis("localhost"); System.out.println("Connected successfully"); //Set Redis string data jedis.set("examplekey", "www.example.com"); //Get the stored data and output it System.out.println("The string stored in Redis is:"+ jedis.get("examplekey")); } }

Compile the above program.

连接成功
redis 存储的字符串为: www.example.com

Redis Java List Example

Example

import java.util.List; import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { //Connect to local Redis service Jedis jedis = new Jedis("localhost"); System.out.println("Connected successfully"); //Store data in the list jedis.lpush("site-list", "Example"); jedis.lpush("site-list", "Google"); jedis.lpush("site-list", "Taobao"); //Get the stored data and output it List<String> list = jedis.lrange("site-list", 0 ,2); for(int i=0; i<list.size(); i++) { System.out.println("The list items are:"+list.get(i)); } } }

Compile the above program.

连接成功
列表项为: Taobao
列表项为: Google
列表项为: Example

Redis Java Keys Example

Example

import java.util.Iterator; import java.util.Set; import redis.clients.jedis.Jedis; public class RedisKeyJava { public static void main(String[] args) { //Connect to local Redis service Jedis jedis = new Jedis("localhost"); System.out.println("Connected successfully"); //Get the data and output it 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.

连接成功
examplekey
site-list
Other Extensions