Redis数据库

一、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命令分别输出zhangsanlisi的成绩信息

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());
    }
}

 

posted @ 2020-10-22 20:04  .HAHA  阅读(337)  评论(0编辑  收藏  举报