一、连接到redis服务
import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("130.51.23.95", 12002); System.out.println("Connection to server sucessfully"); //查看服务是否运行 System.out.println("Server is running: "+jedis.ping()); } }
结果:
二、实例
1、字符串实例
import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //连接本地的 Redis 服务 Jedis jedis = new Jedis("130.51.23.95", 12002); System.out.println("Connection to server sucessfully"); //查看服务是否运行 // System.out.println("Server is running: "+jedis.ping()); jedis.set("item", "001"); System.out.println(jedis.get("item")); } }
结果:
2、列表实例
import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { Jedis jedis = new Jedis("130.51.23.95", 12002); //左边插入 jedis.lpush("list-key2", "item1"); jedis.lpush("list-key2", "item2"); //右边插入 jedis.rpush("list-key2", "item3"); System.out.println(jedis.lrange("list-key2", 0, -1)); //删除 jedis.lpop("list-key2"); System.out.println(jedis.lrange("list-key2", 0, -1));
//查看redis中的所有key
System.out.println(jedis.keys("*"));
}
}
结果:
3、集合
import redis.clients.jedis.Jedis; public class RedisSetJava { public static void main(String[] args) { Jedis jedis = new Jedis("130.51.23.95", 12002); // 插入 jedis.sadd("set-key", "item1"); jedis.sadd("set-key", "item2"); jedis.sadd("set-key", "item3"); System.out.println(jedis.smembers("set-key")); // 查看redis中的所有key System.out.println(jedis.keys("*")); } }
结果:
4、散列
import java.util.HashMap; import java.util.Map; import redis.clients.jedis.Jedis; public class RedisHashJava { public static void main(String[] args) { Jedis jedis = new Jedis("130.51.23.95", 12002); Map<String, String> map = new HashMap<String, String>(); map.put("name", "zhang"); map.put("age", "12"); // 插入 jedis.hmset("hash-key", map); System.out.println(jedis.hgetAll("hash-key")); // 查看redis中的所有key System.out.println(jedis.keys("*")); } }
结果:
三、删除数据
import redis.clients.jedis.Jedis; public class RedisDelJava { public static void main(String[] args) { Jedis jedis = new Jedis("130.51.23.95", 12002); // 查看redis中的所有key System.out.println(jedis.keys("*")); jedis.del("list-key1"); System.out.println(jedis.keys("*")); } }
结果: