一、Redis在Ubuntu上安装
1.安装
sudo apt-get install redis-server
2.卸载
sudo apt-get purge --auto-remove redis-server
3.启动
sudo service redis-server start
4.停止
sudo service redis-server stop
二、命令行操作Redis
Student键值对如下:
zhangsan:{ English: 69 Math: 86 Computer: 77 } lisi:{ English: 55 Math: 100 Computer: 88 } |
(1)用Redis的哈希结构设计出学生表Student(键值可以用student.zhangsan和student.lisi来表示两个键值属于同一个表);
输入redis-cli启动进入命令行客户端
redis-cli
hset student.zhangsan English 69
hset student.zhangsan Math 86
hset student.zhangsan Computer 77
hset student.lisi English 69
hset student.lisi Math 86
hset student.lisi Computer 77
(2)用hgetall命令分别输出zhangsan和lisi的成绩信息;
hgetall student.zhangsan
hgetall student.lisi
(3)用hget命令查询zhangsan的Computer成绩;
hget student.zhangsan Computer
(4)修改lisi的Math成绩,改为95。
hset student.lisi Math 95
三、用JAVA客户端编程Redis
注释redis绑定
执行命令sudo gedit /etc/redis/redis.conf
Ctrl+f查找127.0.0.1,将其注释掉#127.0.0.1
设置requirepass
requirepass字段实际就是redis连接的auth密码
重启redis
service redis-server restart
(1)添加数据:English:45 Math:89 Computer:100
该数据对应的键值对形式如下:
scofield:{ English: 45 Math: 89 Computer: 100 } |
public static void main(String[] args) { // TODO Auto-generated method stub Jedis jedis = new Jedis("192.168.249.128",6379);//虚拟机ip jedis.auth("root");//设置的密码 jedis.hset("student.scofield", "English","45"); jedis.hset("student.scofield", "Math","89"); jedis.hset("student.scofield", "Computer","100"); }
(2)获取scofield的English成绩信息
public static void main(String[] args) { // TODO Auto-generated method stub Jedis jedis = new Jedis("192.168.249.128",6379);//虚拟机ip jedis.auth("root");//设置的密码 Map<String,String> value = jedis.hgetAll("student.scofield"); for(Map.Entry<String, String> entry:value.entrySet()) { //输出scofield的成绩信息 System.out.println(entry.getKey()+":"+entry.getValue()); } }