A nodejs article to master how to use redis and how to use it as a cache

foreword

Redis is a very useful database. The access method of key-value pairs is very simple. It is often used as a cache. How to use as a database cache, redis remote connection failure problem, redis data loss problem, two persistent configurations of RDB and AOF.

Install

windows

Redis official website does not provide window version download, I have uploaded and installed the package: redis-win64 .

linux

Download on the official website: redis official website

start up

windows start as service

Unzip the Redis-x64-3.2.100.zip inside to a suitable location and rename it to Redis.

cmd enters Redis and executes the following command to start the service:

redis-server.exe --service-install redis.windows.conf --loglevel verbose
redis-server --service-start

Other commands:

  1. Uninstall the service:redis-server --service-uninstall
  2. Start the service:redis-server --service-start
  3. Out of service:redis-server --service-stop
  4. Rename service:redis-server --service-name name

linux start as service

Pagoda (recommended)

Pagoda linux can directly install the auto-start service.

Manual installation

decompress

tar -xzvf redis-6.2.6.tar.gz

Enter

cd redis-6.2.6

Install

make & make install

Check whether there is a src or bin directory in the directory, enter the src or bin directory, and start

./redis-server

test

The rest of the content tests are all Windows operations.

cmd into Redis

redis-cli
set test 123
get test

insert image description here

used in nodejs

guide package

npm i redis 

use

Because various operations of redis are asynchronous, we wrap it in an asynchronous function, which is much more convenient.

import {
    
    createClient} from 'redis'

(async () => {
    
    
    //创建redis客户端
    const redis = createClient()
    //连接
    await redis.connect()
    //set
    await redis.set('test', '123')
    //get
    const value = await redis.get('test')
    console.log(value)//123
})()

Use in interface with express

This additionally imports express(service) and cors(resolves cross-domain), and puts all the creations into the scope of the async function .

import express from 'express'
import cors from 'cors'
import path from 'path'
import {
    
    createClient} from 'redis'

(async () => {
    
    
    const app = new express()
    app.use(express.json())
    app.use(cors())
    app.use(express.static(path.resolve('./img')))

    const redis = createClient()
    await redis.connect()

    app.get('/getValue', async (req, res) => {
    
    
        await redis.set('key', 'value')
        const value = await redis.get('key')
        res.send({
    
    value})
    })

    app.listen(3000, () => {
    
    
        console.log('服务器启动')
    })
})()

Front-end testing

<body>
<button onclick="test()">获取信息</button>
<script>
    const test = async () => {
     
     
        const res = await fetch('http://localhost:3000/getValue')
        const data = await res.json()
        console.log(data)
    }
</script>
</body>

insert image description here

redis as database cache

import express from 'express'
import cors from 'cors'
import path from 'path'
import {
    
    createClient} from 'redis'

(async () => {
    
    
    const app = new express()
    app.use(express.json())
    app.use(cors())
    app.use(express.static(path.resolve('./img')))

    const redis = createClient()
    await redis.connect()

    const cache = async (req, res, next) => {
    
    
        //尝试读取缓存中的数据
        const value = await redis.get('key')
        if (value) {
    
    
            res.send({
    
    value: '数据来自缓存:' + value})
        } else {
    
    
            //不存在则去进行数据库读取
            next()
        }
    }

    app.get('/getValue', cache, async (req, res) => {
    
    
        //这里偷个懒用databaseValue代替数据库读取来的数据
        const databaseValue = 'value'
        //用setEx函数存入redis,中间的数字代表缓存时间,这里设置为5秒方便测试
        await redis.setEx('key', 5, databaseValue)
        const value = await redis.get('key')
        res.send({
    
    value: '数据来自数据库:' + value})
    })

    app.listen(3000, () => {
    
    
        console.log('服务器启动')
    })
})()

The front-end content is unchanged, and the test is continuously requested.

We found that the content read from the database will be cached for 5 seconds, and requests within 5 seconds will come from the cache.

When the cache time is up, it is read from the database and stored in the cache again, reducing the pressure on the database.
insert image description here

Redis remote connection failure problem

Windows modifies the redis directory, redis.windows.confand linux modifies it redis.conf.

Commentbind 127.0.0.1 , set Protected Mode Off protected-modeto no.

Reinstall the service again.
insert image description here
insert image description here

redis persistence

Sometimes redis data is easy to be lost accidentally , and we sometimes need to let it save some permanent data, so we need to make persistence.

There are two types of persistence: RDBand AOF.

I am not introducing the interview questions here, so I will not introduce the detailed meanings of the two types in detail, which can be easily understood:

  1. RDBAccording to the rules, the backup data is regularly written to the hard disk, and the backup data is read when the data is lost .

  2. AOFIt is to save your redis operation every time, and if the data is lost, execute the original saved redis operation in turn, and regenerate the corresponding data .

RDB configuration

After redis.confadding the following options, restart the redis service.

save 900 1 # 900s内至少达到一条写命令

save 300 10 # 300s内至少达至10条写命令

save 60 10000 # 60s内至少达到10000条写命令

AOF configuration

After redis.confadding the following options, restart the redis service.

# 开启aof机制
appendonly yes

# aof文件名
appendfilename "appendonly.aof"

# 写入策略,always表示每个写操作都保存到aof文件中,也可以是everysec或no
# always保存每次操作最安全
# everysec每秒保存一次,最多可能会丢失1s数据
# no交给操作系统控制,未知因素更多,最不安全
appendfsync always

# 默认不重写aof文件
no-appendfsync-on-rewrite no

# 保存目录
dir ~/redis/

end words

I believe you have mastered the use of redis when you see here. If you think the article is not bad, please like and collect it. If you have any mistakes or suggestions, you can leave a message, thank you~

Guess you like

Origin blog.csdn.net/weixin_43877799/article/details/123406332