在Java程序中开始使用Redis之前,需要确保已在计算机上设置了Redis Java驱动程序和Java,您可以查看无涯教程的Java教程,以在计算机上安装Java。
现在,看看如何设置Redis Java驱动程序。
您需要从路径下载jedis.jar。确保下载它的最新版本。
您需要将 jedis.jar 包含到类路径中。
连接到Redis服务器
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"); //check whether server is running or not System.out.println("Server is running: "+jedis.ping()); } }
现在,让无涯教程编译并运行上面的程序,以测试与Redis服务器的连接,您可以根据需要更改路径,假设 jedis.jar 的当前版本在当前路径中可用。
$javac RedisJava.java $java RedisJava Connection to server sucessfully Server is running: PONG
Redis Java字符串示例
import redis.clients.jedis.Jedis; public class RedisStringJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //set the data in redis string jedis.set("tutorial-name", "Redis tutorial"); //Get the stored data and print it System.out.println("Stored string in redis:: "+ jedis.get("tutorial-name")); } }
现在,编译并运行上面的程序。
$javac RedisStringJava.java $java RedisStringJava Connection to server sucessfully Stored string in redis:: Redis tutorial
Redis Java列表示例
import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list jedis.lpush("tutorial-list", "Redis"); jedis.lpush("tutorial-list", "Mongodb"); jedis.lpush("tutorial-list", "Mysql"); //Get the stored data and print it 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)); } } }
现在,编译并运行上面的程序。
$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键示例
import redis.clients.jedis.Jedis; public class RedisKeyJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list //Get the stored data and print it List<String> list = jedis.keys("*"); for(int i = 0; i<list.size(); i++) { System.out.println("List of stored keys:: "+list.get(i)); } } }
现在,让无涯教程编译并运行上面的程序。
$javac RedisKeyJava.java $java RedisKeyJava Connection to server sucessfully List of stored keys:: tutorial-name List of stored keys:: tutorial-list
参考链接
https://www.learnfk.com/redis/redis-java.html
标签:Java,redis,Redis,无涯,server,jedis,Jedis From: https://blog.51cto.com/u_14033984/9119739