本文介绍: 1.Redis后台启动推荐)2.Redis相关知识介绍2.1 Redis 键(key)2.2 Redis 字符串(String)2.3. Redis 列表(List)2.4. Redis 集合(Set)2.5. Redis 哈希(Hash)2.6. Redis 有序集合 Zset(sorted set)3.配置文件3.1 单位3.2 INCLUDES 包含3.3 网络相关配置bindprotected-mode3.4GENERAL 通用设置

目录

1.Redis的后台启动(推荐)

2.Redis相关知识介绍

2.1 Redis 键(key)

2.2 Redis 字符串(String)

2.3. Redis 列表(List)


04-概述安装_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Rv41177Af?p=4&vd_source=7b32287884d43c4ae590e89cdf55a096

[root@iZuf6085c1lnhffxqh52xzZ bin]# redis-server /etc/redis.conf
[root@iZuf6085c1lnhffxqh52xzZ bin]# ps -ef | grep redis
root       66433       1  0 19:42 ?        00:00:00 redis-server 127.0.0.1:6379
root       66439   66386  0 19:43 pts/0    00:00:00 grep --color=auto redis
[root@iZuf6085c1lnhffxqh52xzZ bin]# redis-cli
127.0.0.1:6379> 

Redis有五大常用数据类型,分别为:

[root@iZuf6085c1lnhffxqh52xzZ ~]# redis-cli
127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> set k1 caojiajun
OK
127.0.0.1:6379> set k2 jiangwei
OK
127.0.0.1:6379> set k3 icezrj
OK
127.0.0.1:6379> exist k1
(error) ERR unknown command `exist`, with args beginning with: `k1`, 
127.0.0.1:6379> exists k1
(integer) 1
127.0.0.1:6379> exists k4
(integer) 0
127.0.0.1:6379> type k3
string
127.0.0.1:6379> del k3
(integer) 1
127.0.0.1:6379> keys *
1) "k1"
2) "k2"
127.0.0.1:6379> unlink k2
(integer) 1
127.0.0.1:6379> keys *
1) "k1"
127.0.0.1:6379> expire k1 20
(integer) 1
127.0.0.1:6379> keys *
1) "k1"
127.0.0.1:6379> ttl k1
(integer) -2
127.0.0.1:6379> set k2 zeyein
OK
127.0.0.1:6379> set k3 huge
OK
127.0.0.1:6379> keys *
1) "k3"
2) "k2"
127.0.0.1:6379> set k1 icezrj
OK
127.0.0.1:6379> keys *
1) "k1"
2) "k3"
3) "k2"
127.0.0.1:6379> 

 特别注意:-2表示已经过期,-1表示永不过期(del删除unlink删除区别

127.0.0.1:6379> select 1
OK
127.0.0.1:6379[1]> select 4
OK
127.0.0.1:6379[4]> select 0
OK
127.0.0.1:6379> dbsize
(integer) 3
127.0.0.1:6379> flushdb
OK
127.0.0.1:6379> dbsize
(integer) 0
127.0.0.1:6379> flushall
OK
127.0.0.1:6379> 
[root@iZuf6085c1lnhffxqh52xzZ ~]# 

 flushdb和flushall在现实中用的比较少,dbsize表示查看当前库中(key)键的数量。

127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> set k1 v120
OK
127.0.0.1:6379> set k2 v122
OK
127.0.0.1:6379> keys *
1) "k1"
2) "k2"
127.0.0.1:6379> get k1
"v120"
127.0.0.1:6379> get k2
"v122"
127.0.0.1:6379> set k2 v1314
OK
127.0.0.1:6379> get k2
"v1314"
127.0.0.1:6379> append k2 502
(integer) 8
127.0.0.1:6379> get k2
"v1314502"
127.0.0.1:6379> strlen k2
(integer) 8
127.0.0.1:6379> strlen k1
(integer) 4
127.0.0.1:6379> setnx k1 123
(integer) 0
127.0.0.1:6379> decr k2
(error) ERR value is not an integer or out of range
127.0.0.1:6379> set k3 123
OK
127.0.0.1:6379> incr k3
(integer) 124
127.0.0.1:6379> decr k33
(integer) -1
127.0.0.1:6379> decr k3
(integer) 123
127.0.0.1:6379> decr k2
(error) ERR value is not an integer or out of range
127.0.0.1:6379> get k3
"123"
127.0.0.1:6379> incrby k3 10
(integer) 133
127.0.0.1:6379> decrby k3 30
(integer) 103
127.0.0.1:6379> keys *
1) "k1"
2) "k33"
3) "k3"
4) "k2"
127.0.0.1:6379> mset k1 1 k2 2 k3 5
OK
127.0.0.1:6379> mget k1 k2 k3
1) "1"
2) "2"
3) "5"
127.0.0.1:6379> msetnx k1 3 k4 6
(integer) 0
127.0.0.1:6379> msetnx k4 6 k5 66
(integer) 1
127.0.0.1:6379> 

incr是原子操作:所谓原子操作是指不会被线程调度机制打断的操作

Redis set 对外提供的功能list 类似是一个列表的功能特殊之处在于 set 是可以自动排重的,当你需要存储一个列表数据,又不希望出现重复数据时,set 是一个很好的选 择,并且 set 提供了判断某个成员是否在一个 set 集合内的重要接口这个也是 list 所 不能提供的。

Redis hash 是一个键值对集合。 Redis hash 是一个 string 类型field value 映射表,hash 特别适合用于存储对象。 类似 Java 里面的 Map 用户 ID 为查找的 key,存储的 value 用户对象包含姓名,年龄生日信息,如果用 普通的 key/value 结构存储

Redis 有序集合 zset 与普通集合 set 非常相似,是一个没有重复元素的字符串集合。

不同之处是有序集合的每个成员关联了一个评分score),这个评分score)被用 来按照从最低分到最高分的方式排序集合中的成员。集合的成员唯一的,但是评分 可以是重复了 。

因为元素是有序的, 所以你也可以很快的根据评分(score)或者次序(position)来获 取一个范围的元素。 访问有序集合的中间元素也是非常快的,因此你能够使用有序集合作为一个没有重复成 员的智能列表。

安装Redis之后是将配置文件放在了目录/etc/redis.conf下面,使用vi命令将其打开,现在对其进行分析

配置大小单位,开头定义了一些基本度量单位支持 bytes,不支持 bit 大小写敏感

[root@iZuf6085c1lnhffxqh52xzZ ~]# vi /etc/redis.conf

# Redis configuration file example.
#
# Note that in order to read the configuration file, Redis must be
# started with the file path as first argument:
#
# ./redis-server /path/to/redis.conf

# Note on units: when memory size is needed, it is possible to specify
# it in the usual form of 1k 5GB 4M and so forth:
#
# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes
#
# units are case insensitive so 1GB 1Gb 1gB are all the same.

类似 jsp 中的 include,多实例的情况可以把公用的配置文件提取出来

# Include one or more other config files here.  This is useful if you
# have a standard template that goes to all Redis servers but also need
# to customize a few per-server settings.  Include files can include
# other files, so use this wisely.
#
# Note that option "include" won't be rewritten by command "CONFIG REWRITE"
# from admin or Redis Sentinel. Since Redis always uses the last processed
# line as value of a configuration directive, you'd better put includes
# at the beginning of this file to avoid overwriting config change at runtime.
#
# If instead you are interested in using includes to override configuration
# options, it is better to use include as the last line.
#
# include /path/to/local.conf
# include /path/to/other.conf

默认情况 bind=127.0.0.1 只能接受本机访问请求不写的情况下注释后),无限制接受任何 ip 地址访问

本机访问保护模式设置no才能进行远程连接

端口号默认 6379

设置 tcpbacklogbacklog 其实是一个连接队列backlog 队列总和=未完成三次握手 队列 + 已经完成三次握手队列。

在高并发环境下你需要一个高 backlog 值来避免慢客户端连接问题

注意 Linux 内核会将这个值减小到/proc/sys/net/core/somaxconn 的值(128),所以需要 确认增大/proc/sys/net/core/somaxconn 和/proc/sys/net/ipv4/tcp_max_syn_backlog(128) 两个值来达到想要的效果

一个空闲客户端维持多少秒会关闭0 表示关闭功能。即永不关闭

访问客户端的一种心跳检测每个 n 秒检测一次。 单位为秒,如果设置为 0,则不会进行 Keepalive 检测建议设置成 60

是否为后台进程,设置为 yes 守护进程后台启动

存放 pid 文件位置每个实例会产生一个不同pid 文件

指定日志记录级别,Redis 总共支持四个级别debug、verbose、noticewarning,默 认为 notice

日志文件名称(默认为空)

设定库的数量 默认 16,默认数据库为 0,可以使用 SELECT 命令在连接上指定 数据库 id

 

在命令中设置密码,只是临时的。重启 redis 服务器密码还原了。 永久设置,需要再配置文件中进行设置。

在文件下使用“/”可以进行搜索

 

本文就不进行设置了。

设置 redis 同时可以与多少客户端进行连接。

 默认情况下为 10000 个客户端

如果达到了此限制,redis 则会拒绝新的连接请求,并且向这些连接请求方发出 “max number of clients reached”以作回应。

建议必须设置,否则,将内存占满,造成服务器宕机

设置 redis 可以使用的内存量。一旦到达内存使用上限,redis 将会试图移除内部数 据,移除规则可以通过 maxmemorypolicy 来指定。

Redis 发布订阅 (pub/sub) 是一种消息通信模式发送者 (pub) 发送消息订阅者 (sub) 接收消息。 Redis 客户端可以订阅任意数量的频道。

发布订阅命令行实现:

SUBSCRIBE channel1
publish channel1 hello
#返回的 1 是订阅者数量

注:发布消息没有持久化,如果在订阅客户端收不到 hello,只能收到订阅发布消息

Redis 提供了 Bitmaps 这个数据类型”可以实现对位的操作:

命令:setbit

setbit<key> <offset> <value>           设置Bitmaps中某个偏移量的值(0 或1)。
 

统计每个用户是否访问过某个网站。===>

命令:getbit

getbit <key> <offset>                         获取Bitmaps中某个偏移量的值

获取 id=8 的用户是否在 2020-11-06 这天访问过, 返回 0 说明没有访问过:

命令:bitop

计算出两天都访问过网站的用户数量===>

bitop and unique:users:and:20201104_03 unique:users:20201103unique:users:20201104

命令:Bitmaps 与 set 对比

命令: pfadd(去重)

pfadd <key> < element> [element ..]添加指定元素到 HyperLogLog中


将所有元素添加到指定 HyperLogLog 数据结构中。如果执行命令后 HLL 估计的 近似基数发生变化,则返回 1,否则返回 0。

[root@iZuf6085c1lnhffxqh52xzZ ~]# redis-cli
127.0.0.1:6379> pfadd zrj "jiangwei"
(integer) 1
127.0.0.1:6379> pfadd zrj "java"
(integer) 1
127.0.0.1:6379> pfadd zrj "c++"
(integer) 1
127.0.0.1:6379> pfadd zrj "c++"
(integer) 0
127.0.0.1:6379> pfcount zrj 
(integer) 3
127.0.0.1:6379> 

命令:pfmerge(合并)

pfmerge <destkey> <sourcekey> [sourcekey]               将-个或多个HLL合并后的结果存储在另一个HLL中,比如每月活跃用户可以使用每天的活跃用户来合并计算可得

GEO,Geographic,地理信息的缩写。

类型,就是元素的 2 维坐标,在地图上就是经纬度。redis 基于类型,提供了经纬度设置,查询范围查询距离查询经纬度 Hash 等常见操作。

命令:geoadd(添加一个或者多个经纬度坐标

127.0.0.1:6379> geoadd china:city 121.37 31.23 shanghai
(integer) 1
127.0.0.1:6379> geoadd china:city 106.50 29.53 chongqing 114.05 22.52 shenzhen 116.38 39.90 beijing
(integer) 3
127.0.0.1:6379> 

命令:geopos(获取指定位置经纬度

geopos <key> <member> [member..]  获得指定地区的坐标

命令:geodist(获取指定两个位置直线距离

geodist<key> <member1> <member2>[m|km|ft|mi ]     获取两个位置之间的直线距离
 

 命令:georadius范围

georadius<key> < longitude> <latitude>radius  m|km|ft|mi   以给定经纬度中心,找出某一半径内的元素

 由于引入3.2.0版本我们idea报错,于是我们引入2.9.0版本的jedis

<dependencies>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
    </dependencies>

在进行操作之前我们需要确保/etc/redis.conf中的bind 127.0.0.1 -::1是注释完成还有protected-mode yes改成protected-mode no。 之后保存这个文件后再重启一下redis,这里可以在本文开头查看如何重启操作,还有将服务器防火墙规则添加6379端口。(如果是虚拟机则只需要将自己的防火墙关闭 systemctl stop firewalld

package com.atzrj.jedis;

import redis.clients.jedis.Jedis;

/**
 * @Program:jedis_redis
 * @description:jedis
 * @author: 
 * @create: 2022-11-17 11
 **/

public class jedisDemo1 {

    public static void main(String[] args) {
        //创建jedis对象
        Jedis jedis = new Jedis("此处填写自己的虚拟机ip",6379);
        //测试
        String value = jedis.ping();
        System.out.printf(value);
    }


}

 运行后查看我们ping得到的值PONG。

 

 向redis中添加键值k1,k2,k3,并且获取k3的对应值(value):

System.out.println(jedis.exists("k1"));//查看键值k1是否存在
System.out.println(jedis.ttl("k1")); //查看k1还有多少过期,-1 表示永不过期,-2 表示已过期
System.out.println(jedis.get("k1"));

 这里的各种操作和方法可以自行完成,这里不一一演示

要求:

package com.atzrj.jedis;

import java.util.Random;

/**
 * @Program:jedis_redis
 * @description:jedis
 * @author: j
 * @create: 2022-11-17 18
 **/

public class PhoneCode {

    public static void main(String[] args) {
        String code = getCode();
        System.out.println(code);
    }


    //生成位数验证码
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);//生成10以内的值
            code += rand;
        }
        return code;

    }


}

在完成编写一个生成6位数的类之后,还要完成两点钟内有效和每天只能输入三次,两分钟内有效可以想到使用redis中的expire key times 设置键值的过期时间。

 

 如果报上面的错误输入下面这行代码在redis中再次运行即可

config set stop-writes-on-bgsave-error no

 

package com.atzrj.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @Program:jedis_redis
 * @description:jedis
 * @author: j
 * @create: 2022-11-17 18
 **/

public class PhoneCode {

    public static void main(String[] args) {
        //模拟验证码发送
        verifyCode("17779141914");
    }


    //1.生成位数验证码
    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);//生成10以内的值
            code += rand;
        }
        return code;
    }

    //2.每个手机每天只能发送三次验证码放到redis中,设置过期时间
    public static void verifyCode(String phone){
        //连接redis
        Jedis jedis = new Jedis("IP地址", 6379);
        //拼接key
        //手机发送次数key
        String countkey = "VerifyCode"+phone+":count";
        //验证码key
        String codekey  = "VerifyCode"+phone+":code";
        //每个手机每天只能发送三次
        String count = jedis.get(countkey);
            //没有发送次数,第一次发送
            //设置发送次数为1
            if (count==null){
                jedis.setex(countkey,24*60*60,"1");
            }else if (Integer.parseInt(count)<=2){
                //发送次数+1
                jedis.incr(countkey);
            }else if (Integer.parseInt(count)>2){
                //发送三次,不能在发送了
                System.out.println("今天发送次数已达上限!");
                jedis.close();
                return;//不返回验证码仍会更新,虽然次数已经达到上限
            }
        //发送的验证码要放到redis中去
        String vcode = getCode();
        jedis.setex(codekey,120,vcode);
        jedis.close();
        }

    //3.验证校验
    public static void getRedisCode(String phone,String code){
        //从redis中获取验证码
        Jedis jedis = new Jedis("IP地址", 6379);
        //验证码key
        String codekey  = "VerifyCode"+phone+":code";
        String redisCode = jedis.get(codekey);
        //判断
        if (redisCode.equals(code)){
            System.out.println("成功~");
        }else {
            System.out.println("失败!");
        }
        jedis.close();
    }

}




声明本文仅为博主学习redis时的学习笔记

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注