在java程序中使用redis之前,需要确保在机器上安装了redis的java驱动程序和java环境。可以先在将java电脑上并配置好环境。
现在,让我们看看如何设置redis java驱动程序。
jedis.jar
- http://repo1.maven.org/maven2/redis/clients/jedis/2.1.0/jedis-2.1.0-sources.jar ,确保下载的jedis.jar
是最新版本。jedis.jar
包含到类路径中。请参考以下一个简单的示例代码 -
import redis.clients.jedis.jedis;
public class redisjava {
public static void main(string[] args) {
//connecting to redis server on localhost
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
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("tutorialname"));
}
}
执行上面代码,将生成以下结果 -
$javac redisstringjava.java
$java redisstringjava
connection to server sucessfully
stored string in redis:: redis tutorial
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
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