欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java链接redis_动力节点Java学院整理

程序员文章站 2024-02-22 12:11:59
要在java程序中使用使用操作redis,需要确保有redis的java驱动程序和java设置在机器上。现在,让我们来看看如何设置redis的java驱动程序。...

要在java程序中使用使用操作redis,需要确保有redis的java驱动程序和java设置在机器上。现在,让我们来看看如何设置redis的java驱动程序。

  • 需要下载jedis.jar。请一定要下载它的最新版本。
  • 需要包括jedis.jar到你的类路径中。

连接到redis服务器

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

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