您的位置:首页 > 数据库 > Redis

Java 使用 Redis

2016-04-13 21:25 337 查看

安装

开始在 Java 中使用 Redis 前, 我们需要确保已经安装了 redis 服务及 Java redis 驱动Jedis

添加驱动包Jedis



连接到 redis 服务

<span style="font-size:12px;">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");
//查看服务是否运行
System.out.println("Server is running: "+jedis.ping());
}
}</span>


Redis Java String(字符串) 实例

<span style="font-size:12px;">import redis.clients.jedis.Jedis;
public class RedisStringJava {
   public static void main(String[] args) {
      //连接本地的 Redis 服务
      Jedis jedis = new Jedis("localhost");
      System.out.println("Connection to server sucessfully");
      //设置 redis 字符串数据
      jedis.set("w3ckey", "Redis tutorial");
     // 获取存储的数据并输出
     System.out.println("Stored string in redis:: "+ jedis.get("w3ckey"));
 }
}

Connection to server sucessfully
Stored string in redis:: Redis tutorial</span>


Redis Java List实例

<span style="font-size:12px;">import redis.clients.jedis.Jedis;
public class RedisListJava {
public static void main(String[] args) {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
//存储数据到列表中
jedis.lpush("tutorial-list", "Redis");
jedis.lpush("tutorial-list", "Mongodb");
jedis.lpush("tutorial-list", "Mysql");
// 获取存储的数据并输出
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));
}
}
}

Connection to server sucessfully
Stored string in redis:: Redis
Stored string in redis:: Mongodb
Stored string in redis:: Mysql</span>

Redis Java Keys 实例

<span style="font-size:12px;">import redis.clients.jedis.Jedis;
public class RedisKeyJava {
public static void main(String[] args) {
//连接本地的 Redis 服务
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");

// 获取数据并输出
List<String> list = jedis.keys("*");
for(int i=0; i<list.size(); i++) {
System.out.println("List of stored keys:: "+list.get(i));
}
}
}

Connection to server sucessfully
List of stored keys:: tutorial-name
List of stored keys:: tutorial-list</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis memcached