Introduction to redis database, redis download and installation (win64 bit), node operation redis, redis realizes SMS verification registration interface

Introduction to redis:

1: In-memory database, which can also save data to disk;

2: There are more data types than other memory databases:

lists, sets, sorted sets, hash tables, etc.;

3: Master-slave structure: data can be backed up to the slave server;

4: Redis data operation speed is fast;

5: All operations are atomic operations;

Download and install redis service

Like mysql, redis also needs to download and install the redis service. The basic installation is as follows:

1. Download redis from the official website: https://redis.io , enter the official website and click download
insert image description here
2. Redis is not officially supported on Windows. However, you can install Redis on Windows for development by following the instructions below, to install Redis on Windows you first need to enable WSL2 (Windows Subsystem for Linux). WSL2 allows you to run Linux binaries natively on Windows. For this method to work, you need to be running Windows 10 version 2004 and above or Windows 11, related tutorial: https://redis.io/docs/getting-started/installation/, here I do not use this method to install , I went to github to download the project installation, github warehouse address: https://github.com/MSOpenTech/redis or https://github.com/microsoftarchive/redis

3. Redis only provides the win64-bit version. If your computer is 32-bit, you can download the source code to build it into a 32-bit version. The source code address: https://github.com/microsoftarchive/redis, here you can Baidu redis in win32 installation steps.

4. My computer and server are 64-bit. Here I directly download the files built by others for installation. Click the red arrow below to enter the file download page: 5. After entering the
insert image description here
release page, there are two options. Here I choose msi At the end, click Download for the configured installation package, put the downloaded program into a certain folder and create a new folder with the program name (of course, you don’t need to create a new folder here, it’s convenient for me to install all service software in the same A certain root folder under a disk), then double-click the arrow to install the program:
insert image description here6. Agree to the agreement and continue:
insert image description here
7. Here I change the installation directory and automatically configure the path environment variable, and then click next, such as:
insert image description here
8. Configure the port number and configure the firewall. Here I use the default. Of course, the online project can change the default port number, such as:
insert image description here
9. The memory limit is not checked by default. Here I checked the memory limit and limited the maximum storage of 100Mb data, of course It can be unchecked, and you can configure it yourself in the configuration file later:
insert image description here
10. Finally, click install to install, such as:
insert image description here
11. At this time, the computer may pop up a box to prompt you to click (yes to allow), and finally click finish to complete the installation
insert image description here
. 12. The installation is complete After that, I usually delete the installation program and keep the service program, such as:
insert image description here
13. Go to the root directory of the installation package, open the doc document pointed by the arrow to see the basic introduction of each file, such as:
insert image description here
14. Still need to know The following three files, among which the redis.windows.conf file is editable, is the configuration information for the redis service, in which you can set the port, memory size limit, etc., such as the
insert image description here
description of some parameters in the configuration file:

# 配置端口:
port 6379
# 
tcp-backlog 511
# 只允许某些ip可以访问,可以避免攻击,默认是不打开的,这里我自己打开了
bind 127.0.0.1
# 
timeout 0
# 
tcp-keepalive 0
# 
loglevel notice
# 配置日志打印文件地址,如果没有指定路径就会打印到控制台
logfile ""
# 数据库数量配置,redis数据库数量不像mysql可以任意添加,redis只能通过配置的方式指定,redis服务启动后就会生成指定数量的数据库,redis数据库是以数字自动命名的,默认使用第一个数据库,即索引为0的数据库
databases 16
# 备份数据到磁盘 ,save 时间间隔 变化键数量 ,表示多少秒后有几个键被修改时才会备份,时间没到是不会备份的
save 900 1
save 300 10
save 60 10000
# 
stop-writes-on-bgsave-error yes
# 当某些数据被保存到磁盘中时是否进行压缩,压缩可节省控件但是不利于cpu
rdbcompression yes
# 
rdbchecksum yes
# 保存到磁盘数据文件的名称,数据保存到磁盘后,每次使用数据时会从磁盘中读取,可以提升速度
dbfilename dump.rdb
# 保存到磁盘文件的路径
dir ./
# 
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-entries 512
list-max-ziplist-value 64
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
#
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes

15. At this time, we can start the command line with Win+R and start the redis service on the command line. Here, for convenience, I write a startup script ending with bat (start_redis_server.bat) and double-click to start it. The start_redis_server.bat startup script code is:

redis-server.exe redis.windows.conf

16. At this time, we double-click the start_redis_server.bat file to see the black window flashing past, and then we can see that the redis service has been running in the service!
insert image description here
17. Start the redis client. At this time, you can double-click redis-cli.exe, and a client with 127.0.0.1:6379 will be started. At this time, you can perform operations such as adding, deleting, modifying and checking data in this window. Normally, I will Write a program at the end of bat (redis_client.bat) to specify the ip and port to connect to the remote server, connect to the remote server script, the redis_client.bat script is as follows (actually, just write the server ip and port):

redis-cli.exe -h 127.0.0.1 -p 6379

set redis password

1. Through the above installation of redis, you can know the basic startup connection to redis. You can find that the difference from installing mysql is that you do not enter a password. This is because redis does not require a password by default. Of course, you can set a password yourself. The command is (note that strict case):

CONFIG set requirepass '你自己的密码'

insert image description here
2. Password verification: After setting the password and exiting the client and re-entering, it will prompt that the redis cannot be operated without password verification. At this time, password verification can be performed (only one verification is required each time you enter the client), password verification Command (note case): such as

AUTH '你的密码'

insert image description here
3. Password expiration time, when the redis service is closed, the password will become invalid when re-entering the redis service.

Terminal operation redis database:

1. Operate data in a key-value manner:

//存数据:set key value ,如果key相同的话,后面的value会覆盖前面相同的key的值 如:set name '小明'
//读数据:get key 如:get name
//判断数据是否存在:exists key 如: exists name
//删除数据:del key  如:del name

2. Operate the database in the form of a hash table:

//存数据: hmset key(主键) 字段1 值1 字段2 值2 ,如: hmset user_1 name '小明' age 18
//查某个key下所有字段数据: hgetallkey key 如:hgetall user_1 
//查某个key下某个字段是否存在:hexists key 字段 如:hexists user_1 name
//查某个key下某个字段的值:hget key 字段 或 hmget key 字段 如:hget user_1 name 或 hmget user_1 name
//查某个key下所有字段:hkeys key 如 :hkeys user_1

3. Operate the database in list form:

A list is similar to an array, and each key represents an array, as follows:

//往数组左边(前面)存数据:lpush key value , 如:lpush arr1 A
//往数据右边(后面)存数据:rpush key value , 如:rpush arr1 B
//从某个索引开始列出到某个索引结束的数据:larnge key start stop 如:larnge arr1 0 2
//从左边/右边删除某个列表值:lpop/rpop key 如:lpop arr1 

4. Ordered collection:

Ordered sets can generally be used for weight sorting, and the specific usage is as follows:

//添加要排序的元素:zadd key 权重 值,如:zadd grade 10 a
//根据权重排序显示前几位值:zrange key start stop 如:zrange grade 0 10
//根据权重排序显示权重分值和值:zrange key start stop withscopes

Note : The ones with small weights will be displayed first, and the ones with large weights will be displayed last. It should be noted that, including the above list, the last added element will be displayed at the front (based on lpush).

nodejs operation redis:

Redis is a database that supports multiple languages. Here I take nodejs to operate redis as an example to briefly introduce the steps of using redis in programming.

The nodejs operation redis can use a third-party client module based on node to realize redis communication. The specific steps are as follows:

1. Download and install the redis package: Note that an error will be reported if the redis version is too high during the test. I am using [email protected] here

npm install redis@3.1.2

2. Introduce redis in the file that needs to be used:

const redis = require('redis')

3. Create a redis client:

const redisClient = redis.createClient(option)

4. Call the api of the redis client, taking set as an example:

redisClient.set(key,value,callback)

The actual development of node is used as follows:

Encapsulate the redis client:

// 导入redis缓存包:
const redis = require('redis')
// 配置信息:
const option = {
    
    
  host: '127.0.0.1',
  port: 6379,
  db: 0, // redis数据库以数字表示,这里是和mysql之间的区别
  // password: '123456a',
  detect_buffers: true, // 传入buffer 返回也是buffer 否则会转换成String
  retry_strategy: function (opt) {
    
    
    // 重连机制
    if (opt.error && opt.error.code === "ECONNREFUSED") {
    
    
      return new Error("The server refused the connection")
    }
    if (opt.total_retry_time > 1000 * 60 * 60) {
    
    
      return new Error("Retry time exhausted")
    }
    if (opt.attempt > 10) {
    
    
      // End reconnecting with built in error
      return undefined
    }
    // reconnect after
    return Math.min(opt.attempt * 100, 3000)
  }
}

// 创建redis客户端
const redisClient = redis.createClient(option)

// 准备连接redis-server事件
redisClient.on('ready', function () {
    
    
  // console.log('Redis redisClient: ready')
})

// 连接到redis-server回调事件
redisClient.on('connect', function () {
    
    
  // console.log('redis is now connected!')
})

redisClient.on('reconnecting', function () {
    
    
  // console.log('redis reconnecting')
})

redisClient.on('end', function () {
    
    
  // console.log('Redis Closed!')
})

redisClient.on('warning', function (err) {
    
    
  console.log('Redis redisClient: warning,'+ err)
})

redisClient.on('error', function (err) {
    
    
  console.error('Redis Error ' + err)
})

// 导出redis客户端:
module.exports = redisClient

Call the api in node_redis, which is the same as the command in the command line. Take the SMS registration user interface as an example as follows (note: some modules in the interface are not introduced, but they are not subject to learning, and you can embed your own interface in the actual test to achieve the effect):

Encapsulate the SMS module:

// 引入redis客户端:
const redisClient = require('./redisconf')
// 发短信功能模块的封装:
//调用阿里短信平台的框架
const SMSClient = require('@alicloud/sms-sdk')
//短信云平台获取accessKeyId(下面是假值)
const accessKeyId = 'AeAm*******j5LTrKLJV'
//短信云平台获取accessKeySecret(下面是假值)
const secretAccessKey =  'TfRSFe*********56eWvPwwZ44J8C'
//创建一个发送短信的实例
let smsClient = new SMSClient({
    
    accessKeyId,secretAccessKey})

//发送短信功能封装为函数供其它需要发送短信的地方调用
let sendSmsCode = async (phone,verCode) => {
    
    
  try {
    
    
    // 校验参数是否为空:
    if (!phone) throw ('缺少号码')
    if (!verCode) throw ('缺少验证码')

    // 配置请求参数:
    let dataToSend = {
    
    
      //传入手机号码
      PhoneNumbers: phone,
      //短信云平台获取签名
      SignName:'苦海',
      //短信云平台获取模板编码(下面是假值)
      TemplateCode:'SMS_36*****888',
      //将对象转换为json字符串后赋值给后面TemplateParam
      TemplateParam: JSON.stringify({
    
     code: verCode })
    }

    //调用smsClient实例的方法:sendSMS,通知阿里云发送验证码
    let smsResponse = await smsClient.sendSMS(dataToSend)
    // 结构出Code状态码判断是否发送成功
    let {
    
     Code } = smsResponse
    // 发送成功后将验证码以手机号码为key,验证码为value的方式,临时存到redis中并将结果返回给方法sendLoginCroeCode调用者,这里不返回也没问题,可以不用返回,因为发短信和注册接口是两个独立的接口,只是验证码需要临时存到redis中
    if (Code === 'OK') {
    
    
      // 将验证码和号码存到redis缓存中,以号码为key,验证码为value形式:
      redisClient.set(phone,verCode,(err) => {
    
    
        if (err) {
    
    
          console.log('验证码存到redis错误:' + err)
        }
      })
      // 设置60秒过期时间,无论是否校验通过,60秒后都清楚数据
      redisClient.expire(phone,60)
      // 将结果返回调用者
      return smsResponse
    }
    // 当发送失败时抛出异常:
    throw '短信发送失败!'
  } catch (error) {
    
    
    console.log('发送短信验证码失败,您的操作可能过于频繁,请稍微再试!'+error)
  }
}

// 导出此方法:
module.exports = sendSmsCode

Send SMS interface:

// 引入redis客户端:
const redisClient = require('../config/redisconf')
// 获取短信验证码接口
router.post('/api/regist',(request,response)=>{
    
    
  let {
    
    phone} = request.body
  let smsCode = String(1000 + parseInt(Math.random() * 1000000)).slice(0, 4)
  // 调用发短信方法进行发送验证码:
  let verCode = sendSmsCode(phone,smsCode)
  if (verCode) {
    
    
    response.send({
    
    cod: 200, msg: '获取短信验证码成功!'})
  } else {
    
    
    response.send({
    
    cod: 201, msg: '获取短信验证码失败!'})
  }
})

Verification code verification and registration:

// 注册用户接口:
router.post('/api/register',(request,response) => {
    
    
    const {
    
    userName, passWord, phone, authCode} = request.body
    let sql1 = 'SELECT * FROM `theuser` WHERE user_name = "'+userName+'"'
    // 判断此用户是否存在
    function isExistUserName () {
    
    
        return new Promise((resolve) => {
    
    
            connection.query(sql1,(error, results) => {
    
    
                try {
    
    
                    if (error) {
    
    
                        throw error
                    } else {
    
    
                        resolve(results)
                    }
                } catch (err) {
    
    
                    console.log('regestserve文件注册用户接口中判断此用户是否存在错误:' + err)
                }
            })
        })
    }
    // 新增用户:
    async function addNewTheuser () {
    
    
        // 查询用户名是否存在
        let isExist = await isExistUserName()
        // 用户名不存在时
        if (isExist.length === 0) {
    
    
            // 自己封装的获取当前时间并格式化的函数:
            let timer = dateFormatter1()
            let sql2 = "INSERT INTO `projectdataroot`.`theuser` (`user_name`, `user_password`, `user_phone`, `user_create_date`) VALUES ('"+userName+"', '"+passWord+"', '"+phone+"', '"+timer+"')"
            // 从redis中获取验证码并做校验:
            redisClient.get(phone,(error,smsCode)=>{
    
    
                if (error) {
    
    
                    throw error
                } else {
    
    
                    // 判断验证码是否正确
                    if (authCode === smsCode) {
    
    
                        connection.query(sql2,(error)=>{
    
    
                            try {
    
    
                                if (error) {
    
    
                                    throw error
                                } else {
    
    
                                    response.send({
    
    cod: 200, msg: '注册成功!'})
                                    // 注册成功后立即删除redis中的校验码
                                    redisClient.del(phone,(error=>{
    
    
                                        if (error) {
    
    
                                            console.log('删除redis短信验证码数据失败:'+ error)
                                        }
                                    }))
                                }
                            } catch (err){
    
    
                                console.log('regestserve文件注册用户接口中新增用户存在错误:' + err)
                            }
                        })
                    } else {
    
    
                        response.send({
    
    cod: 202, msg: '短信验证码不正确!'})
                    }
                }
            })
        } else {
    
    
            response.send({
    
    cod: 201, msg: '用户已存在!'})
        }
    }
    addNewTheuser()
})

Tips: The pictures and other materials in this article come from the Internet. If there is any infringement, please send an email to the mailbox: [email protected] to contact the author to delete it.
Author: sea of ​​bitterness

Guess you like

Origin blog.csdn.net/weixin_46758988/article/details/126880957