当前位置:网站首页>[Architect (Part 41)] installation of server development and connection to redis database
[Architect (Part 41)] installation of server development and connection to redis database
2022-06-24 11:29:00 【A tailed Warbler】
Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 24 God , Click to see the event details
Local installation Redis
download
Go to the download address , I downloaded this
Local installation
I unzip it here to D Dish up , That's all the files .
Use vscode Open this file
find requirepass foobared, Copy to a new line , Ahead of # Delete , And clear the space , Otherwise, the password will not be set successfully .
And then foobared Change it to the password you need , Then save , If the identity is not enough, open it as an administrator .
stay redis The folder is open cmd, perform redis-server.exe redis.windows.conf, At this time, the interface shows redis Information , Indicates that the service is on normally .
In order to facilitate the next startup , stay redis Create a new folder under the folder startup.bat file , The content is redis-server.exe redis.windows.conf.
Don't close this window , Continue opening one cmd, perform redis-cli.exe -h 127.0.0.1 -p 6379 -a xiaowei123 enter
among xiaowei123 That's the password you set up before .
And then use set key value Set the cache , Use get key Read cache , The following interface shows that the local installation is successful .
Connect Redis
Install... In the project Redis
Here in order to follow the teacher to learn , Specify the installation version , Different syntax in the new version will lead to errors .
npm i [email protected]3.0.2 -S
To configure Redis
// src\config\envs\dev.js
module.exports = {
// redis Connection configuration
redisConf: {
port: '6379',
host: '127.0.0.1',
password: 'xiaowei123'
},
}
Package settings / Access to the cache
// src\cache\index.js
const redisClient = require('../db/redis')
/** * redis set * @param {string} key key * @param {string|Object} val val * @param {number} timeout Expiration time , Company s , Default 1h */
function cacheSet(key, val, timeout = 60 * 60) {
let formatVal
if (typeof val === 'object') {
formatVal = JSON.stringify(val)
} else {
formatVal = val
}
redisClient.set(key, formatVal)
redisClient.expire(key, timeout)
}
/** * redis get * @param {string} key key */
function cacheGet(key) {
const promise = new Promise((resolve, reject) => {
redisClient.get(key, (err, val) => {
if (err) {
reject(err)
return
}
if (val == null) {
resolve(null)
return
}
try {
resolve(JSON.parse(val))
} catch (ex) {
resolve(val)
}
})
})
return promise
}
module.exports = {
cacheSet,
cacheGet,
}
Test connection Redis database
// src\db\redis.js
const redis = require('redis')
const { redisConf } = require('../config/index')
// Create client
const { port, host, password } = redisConf
const opt = {}
if (password) {
opt.password = password // prd The environment requires a password
}
const redisClient = redis.createClient(port, host, opt)
redisClient.on('error', err => {
console.error('redis connect error', err)
})
// function node src/db/redis.js Make a test connection
redisClient.on('connect', () => {
console.log('redis connect success')
redisClient.set('foo', 'bar', redis.print) // => "Reply: OK"
redisClient.get('foo', redis.print) // => "Reply: bar"
redisClient.quit()
})
module.exports = redisClient
Console execution node src/db/redis.js, appear success It means the connection is successful .
Further test the database connection
// src\routes\index.js
const router = require('koa-router')()
const packageInfo = require('../../package.json')
const testMysqlConn = require('../db/mysql2')
const ENV = require('../utils/env')
const { WorkModel } = require('../models/WorksModel')
const { cacheGet, cacheSet } = require('../cache/index')
// Test database connection
router.get('/api/db-check', async (ctx) => {
// test mysql Database connection
const mysqlRes = await testMysqlConn()
// test mongodb Database connection
let mongodbConn
try {
mongodbConn = true
await WorkModel.findOne()
} catch (error) {
mongodbConn = false
}
// test Redis Connect
cacheSet('name', 'biz editor sever OK - by redis')
const redisTestVal = await cacheGet('name')
ctx.body = {
errno: 0,
data: {
name: 'biz editor server',
version: packageInfo.version,
ENV,
mysqlConn: mysqlRes.length > 0,
mongodbConn,
redisConn: redisTestVal != null,
}
}
})
module.exports = router
visit http://localhost:3000/api/db-check,redisConn As the result of the true, It also further proves that Redis Database connection succeeded .
边栏推荐
- Example of PHP observer mode [useful in the laravel framework]
- ≥ 2012r2 configure IIS FTP
- “一个优秀程序员可抵五个普通程序员!”
- How to export only the titles in word documents? (i.e. delete all the text contents and keep only the title) stop B
- @RequestBody注解
- 初识string+简单用法(一)
- 如何开发短信通知和语音功能医院信息系统(HIS系统)
- Today in history: Turing's birth day; The birth of the founder of the Internet; Reddit goes online
- [深度学习][pytorch][原创]crnn在高版本pytorch上训练loss为nan解决办法
- 《opencv学习笔记》-- CV::Mat类
猜你喜欢
![[activities this Saturday] NET Day in China](/img/33/c0e8eeb8f673232a7c27bbaf5e713f.jpg)
[activities this Saturday] NET Day in China

如何优雅的写 Controller 层代码?

【本周六活动】.NET Day in China

保险APP适老化服务评测分析2022第06期

脚本之美│VBS 入门交互实战

程序员大部分时间不是写代码,而是。。。

软件测试 对前一日函数的基本路径测试

Basic path test of software test on the function of the previous day

《opencv学习笔记》-- 离散傅里叶变换

Déplacer Tencent sur le cloud a guéri leur anxiété technologique
随机推荐
When the data security law comes, how can enterprises prepare for a rainy day? Tencent security has something to say
Internship experience sharing in ByteDance 𞓜 ten thousand word job guide
工具及方法 - 在Source Insight中使用代码格式化工具
The record of 1300+ times of listing and the pursuit of ultimate happiness
Give you a server. Can you deploy your code online?
5W1H talk about open source - what is open source?
Network monitoring: active troubleshooting becomes simple
脚本之美│VBS 入门交互实战
Google Earth Engine(GEE)—如何新增一个图例在Map面板
Does the depth system work?
如何优雅的写 Controller 层代码?
How to improve the quality of Baidu keyword?
分布式系统解决之道:目录、消息队列、事务系统及其他
Many of my friends asked me what books and online classes I recommended. This time, I contributed all the materials that I had been hiding for a long time (Part 1)
Install wpr Exe command
Nacos source code - configure automatic update
Why should we make the best use of the external chain in SEO?
如何只导出word文档中的标题?(即将正文内容都删除,只保留标题)B站牛逼
[latest - lightweight cloud servers - hot sales] new lightweight application server optimization scheme, 1-core 2g5m time limit as low as 99 yuan / year
Oxylabs live online: website capture demo