一、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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
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"
));
}
}
|
三、参考
网上找了两篇关于Redis的博客,记录下!
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/5671597.html,如需转载请自行联系原作者