当前位置:网站首页>Redis learning - 06 drifting bottle case
Redis learning - 06 drifting bottle case
2022-06-26 12:36:00 【Preserved egg is very white】
Case introduction
Wechat has hundreds of millions of users , At one time, there may be thousands of people playing with drifting bottles at the same time , For such a service with high concurrency and small amount of data , Use Node.js and Redis It is definitely a recommended choice .
Interface design
Throw a drift bottle
- Request method :
POST - Request path :
/ - Request body parameters :
time: The timestamp of the bottle thrown , The default setting isDate.now()owner: Drifting bottle owner ( user id)type: Drift bottle typemale: menfemale: women
content: Contents of the drifting bottle
- return : Complete data content
Pick up a drifting bottle
- Request method :
GET - Request path :
/ - Query parameters :
user: The man who picks up the drifting bottle ( user id)type: Drift bottle typeall: Allmale: menfemale: women
- Return the data :
{
"time": 1641883884765, // The timestamp of the bottle thrown
"owner": 1, // Drifting bottle owner
"type": "male", // Drift bottle type
"content": "hello world" // Contents of the drifting bottle
}
Design thinking
Can be Redis Imagine a sea ,Redis Every one of them Hash Type of data is a drifting bottle , Each drifting bottle has a unique id( namely Redis The key ), It contains some information about the drifting bottle ( namely Redis The key value ).
Use two databases , Store two types of type Drifting bottle , The purpose is to facilitate the use of Redis Medium RANDOMKEY command , This command returns a random key in the current database , Without any conditions .
When throwing a drift bottle , Create a unique id( Use uuidv4), With this id by key, The data of the drift bottle is the value , Add one Hash Data of type , And set up 1 Days .
When picking up drifting bottles , according to type Decide which database to randomly read data from , Once the drifting bottle is picked up , Just delete from the database .
Start developing
Initialize project
mkdir drift-bottle
cd drift-bottle
npm init -y
npm i express ioredis uuidv4
app.js:
const {
uuid } = require('uuidv4')
const Redis = require('ioredis')
const express = require('express')
const app = express()
app.use(express.json())
// establish Redis example
const connectRedis = () => {
return new Redis()
}
// Throw a drift bottle
app.post('/', (req, res, next) => {
try {
res.send('post /')
} catch (error) {
next(error)
}
})
// Pick up a drifting bottle
app.get('/', (req, res, next) => {
try {
res.send('get /')
} catch (error) {
next(error)
}
})
// Unified handling of exceptions
app.use((err, req, res, next) => {
res.status(500).json({
error: err.message
})
})
app.listen(3000, () => {
console.log('runnning')
})
Throw a drift bottle
// Throw a drift bottle
app.post('/', async (req, res, next) => {
try {
const bottle = req.body
// Set timestamp
bottle.time = bottle.time || Date.now()
// Randomly generate a non repeating... For each drift bottle id
const bottleId = uuid()
const type = {
male: 0,
female: 1
}
await redis
.pipeline()
// Switch databases according to type
.select(type[bottle.type])
// Save the data as Hash
.hmset(bottleId, bottle)
// Set up 1 Days
.expire(bottleId, 24 * 60 * 60)
.exec()
res.status(201).json({
bottle: {
id: bottleId,
...bottle
}
})
} catch (error) {
next(error)
}
})
Pick up a drifting bottle
// Pick up a drifting bottle
app.get('/', async (req, res, next) => {
try {
const query = req.query
const type = {
all: Math.round(Math.random()),
male: 0,
female: 1
}
query.type = query.type || 'all'
// Switch databases according to type
await redis.select(type[query.type])
// Pick one at random key
const bottleId = await redis.randomkey()
if (!bottleId) {
res.status(200).json({
message: ' The sea is clean ...'
})
}
// According to the drift bottle id Get complete drift bottle information
const bottle = await redis.hgetall(bottleId)
res.status(201).json({
bottle
})
// from Redis Delete the found drift bottle
redis.del(bottleId)
} catch (error) {
next(error)
}
})
边栏推荐
- PHP laravel+gatewayworker completes im instant messaging and file transfer (Chapter 1: basic configuration)
- Scala problem solving the problem of slow SBT Download
- Omni channel member link - tmall member link 3: preparation of member operation content
- Redis learning - 01 introduction, installation and configuration
- Leetcode 78. Subset and 90 Subset II
- Ubuntu安装配置PostgreSQL(18.04)
- Thinkphp5 query report: sqlstate[hy093]: invalid parameter number
- Adobe Acrobat阻止30款安全软件查看PDF文件 或存在安全风险
- How to do well in member marketing three steps to teach you to understand member management
- Nodejs framework express and KOA
猜你喜欢
![[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure](/img/d2/a6cbb0abe9e04c412d1f6021430528.png)
[redis series] redis learning 16. Redis Dictionary (map) and its core coding structure

Omnichannel membership - tmall membership 1: opening tutorial

Redis learning - 02 common data types, operation commands and expiration time

Spark-day03-core programming RDD operator

PHP uses laravel pay component to quickly access wechat jsapi payment (wechat official account payment)
The loss of female scientists

JS get the current screen height method and listen for DOM elements to enter the viewport

"Pinduoduo and short video speed version", how can I roast!

不到40行代码手撸一个BlocProvider

Examples of how laravel uses with preload (eager to load) and nested query
随机推荐
The loss of female scientists
How do consumer goods enterprises formulate membership interests?
Leetcode 78. Subset and 90 Subset II
Five trends of member marketing of consumer goods enterprises in the future
初探Protostuff的使用[通俗易懂]
SQL injection in Pikachu shooting range
sqlalchemy event listen Automatic generate CRUD excel
Wechat applet wx Request request encapsulation
Build Pikachu shooting range and introduction
Assembly language (7) operation instruction
大智慧哪个开户更安全,更好点
PHP returns false when calling redis method decrby less than 0
Iframe usage and contentwindow, parent and PostMessage communication methods
Laravel+gatewayworker completes the im instant messaging and file transfer functions (Chapter 4: server debugging errors)
JS get the current screen height method and listen for DOM elements to enter the viewport
2022 edition of investment analysis and "fourteenth five year plan" development prospect forecast report of China's switchgear industry
5+API,清除应用缓存
Five trends of member management in 2022
7-16 货币系统Ⅰ
2022 China smart bathroom cabinet Market Research and investment Competitiveness Analysis Report