Before starting to use Redis in Java, we need to ensure that the redis service and Java redis driver have been installed, and that 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 You need to download the driver package and download jedis.jar. Make sure to download the latest driver package. (Recommended learning: Redis Video Tutorial)
Include this driver package in your classpath.
Connect to the redis service
Example
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 above Java program and make sure the path to the driver package is correct.
连接成功 服务正在运行: PONG
Redis Java String (string) Example
Example
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("runoobkey", "www.php.cn"); // 获取存储的数据并输出 System.out.println("redis 存储的字符串为: "+ jedis.get("runoobkey")); } }
Compile the above program.
连接成功 redis 存储的字符串为: www.php.cn
The above is the detailed content of How to use redis in java. For more information, please follow other related articles on the PHP Chinese website!