Java链接redis_动力节点Java学院整理
要在Java程序中使用使用操作Redis,需要确保有Redis的Java驱动程序和Java设置在机器上。现在,让我们来看看如何设置Redis的Java驱动程序。
- 需要下载jedis.jar。请一定要下载它的最新版本。
- 需要包括jedis.jar到你的类路径中。
连接到Redis服务器
importredis.clients.jedis.Jedis; publicclassRedisJava{ publicstaticvoidmain(String[]args){ //ConnectingtoRedisserveronlocalhost Jedisjedis=newJedis("localhost"); System.out.println("Connectiontoserversucessfully"); //checkwhetherserverisrunningornot System.out.println("Serverisrunning:"+jedis.ping()); } }
现在,让我们来编译和运行上面的程序来测试连接Redis服务器。你可以根据实际情况改变路径。这里假设jedis.jar的当前版本在当前路径中可用
$javacRedisJava.java $javaRedisJava Connectiontoserversucessfully Serverisrunning:PONG
Redis和Java字符串实例
importredis.clients.jedis.Jedis; publicclassRedisStringJava{ publicstaticvoidmain(String[]args){ //ConnectingtoRedisserveronlocalhost Jedisjedis=newJedis("localhost"); System.out.println("Connectiontoserversucessfully"); //setthedatainredisstring jedis.set("tutorial-name","Redistutorial"); //Getthestoreddataandprintit System.out.println("Storedstringinredis::"+jedis.get("tutorial-name")); } }
现在,让我们编译并运行上述程序。
$javacRedisStringJava.java $javaRedisStringJava Connectiontoserversucessfully Storedstringinredis::Redistutorial
Redis和Java列表示例
importredis.clients.jedis.Jedis; publicclassRedisListJava{ publicstaticvoidmain(String[]args){ //ConnectingtoRedisserveronlocalhost Jedisjedis=newJedis("localhost"); System.out.println("Connectiontoserversucessfully"); //storedatainredislist jedis.lpush("tutorial-list","Redis"); jedis.lpush("tutorial-list","Mongodb"); jedis.lpush("tutorial-list","Mysql"); //Getthestoreddataandprintit Listlist=jedis.lrange("tutorial-list",0,5); for(inti=0;i 现在,让我们编译并运行上述程序。
$javacRedisListJava.java $javaRedisListJava Connectiontoserversucessfully Storedstringinredis::Redis Storedstringinredis::Mongodb Storedstringinredis::MysqlRedis和Java的键实例
importredis.clients.jedis.Jedis; publicclassRedisKeyJava{ publicstaticvoidmain(String[]args){ //ConnectingtoRedisserveronlocalhost Jedisjedis=newJedis("localhost"); System.out.println("Connectiontoserversucessfully"); //storedatainredislist //Getthestoreddataandprintit Listlist=jedis.keys("*"); for(inti=0;i 现在,让我们编译并运行上述程序。
$javacRedisKeyJava.java $javaRedisKeyJava Connectiontoserversucessfully Listofstoredkeys::tutorial-name Listofstoredkeys::tutorial-list