一、Redis 的安装
1.Redis 下载
Windows 版本下载:https://github.com/dmajkic/redis/downloads
2.解压到
C:\redis-2.4.5-win32-win64
3.启动Redis server
4. 启动Redis 客户端
redis-cli.exe -h 127.0.0.1 -p 6379
5. 测试Redis
二、Java中使用redis
public class RedisJava { public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
//jedis.auth("123456");
System.out.println("Connection success");
System.out.println("Serving is running: " + jedis.ping()); //testString(jedis); //testMap(jedis);
String key = "author";
jedis.sadd(key, "zhangsan");
jedis.sadd(key, "lisi");
jedis.sadd(key, "wangwu");
jedis.sadd(key, "zhaoliu"); jedis.srem(key, "zhaoliu"); // 移除zhaoliu
jedis.expire(key, 2);
System.out.println(jedis.smembers(key));//输出set中所有数据 try {
Thread.sleep(3000);
} catch (InterruptedException e) {
} System.out.println("查看author的剩余生存时间:" + jedis.ttl(key));
// 移除某个key的生存时间
System.out.println("移除author的生存时间:" + jedis.persist(key));
System.out.println("查看author的剩余生存时间:" + jedis.ttl(key));
System.out.println(jedis.smembers(key));//输出set中所有数据 } private static void testMap(Jedis jedis) {
String key = "student";
Map<String, String> map = new HashMap<String,String>();
map.put("name", "zhangsan");
map.put("age", "100");
map.put("sex", "male");
jedis.hmset(key, map); List<String> stuList = jedis.hmget(key, "name","age","sex");
System.out.println(stuList); System.out.println("student中的所有key: " + jedis.hkeys(key));
System.out.println("student中的所有value: " + jedis.hvals(key)); System.out.println("-----------------------------------------");
Iterator<String> iterator = jedis.hkeys(key).iterator();
while (iterator.hasNext()) {
String itemKey = iterator.next();
String itemValue = jedis.hget(key, itemKey);
System.out.println("itemKey: " + itemKey + " itemValue: " + itemValue); }
System.out.println("-----------------------------------------"); jedis.hdel(key, "sex");
System.out.println("student 是否存在: " + jedis.exists(key));
System.out.println("student 长度: " + jedis.hlen("student"));//sex 已经删除,所以长度为2
System.out.println(jedis.hmget(key, "name","sex")); //sex 已经删除,所以为null
} private static void testString(Jedis jedis) {
jedis.set("address", "hangzhou ");
System.out.println("address: " + jedis.get("address")); jedis.append("address", "west lake");//拼接
System.out.println("address: " + jedis.get("address")); jedis.del("address");
System.out.println("address: " + jedis.get("address")); jedis.mset("name","zhangsan","sex","male","age","100");
jedis.incr("age");
System.out.println(jedis.get("name") + " " + jedis.get("age") + " " + jedis.get("sex"));
} }