How to use Redis and TypeScript to develop cache penetration defense function
Cache penetration refers to when the user queries a non-existent data, because there is no corresponding data in the cache The data will directly access the database every time, causing excessive pressure on the database. In order to solve this problem, we can use Redis and TypeScript to develop cache penetration defense functions.
1. Install and configure Redis
First, we need to install Redis and configure it. On Ubuntu systems, Redis can be installed with the following command:
sudo apt-get install redis-server
After the installation is complete, Redis will run in local mode and listen to the default port 6379 by default. Then, we need to configure some parameters of Redis for use.
In the Redis configuration file, find the following configuration and uncomment it:
# bind 127.0.0.1 ::1
Modify it to:
bind 0.0.0.0
In this way, Redis will be able to run on IP addresses other than local Monitor.
Save and exit the configuration file, and then restart the Redis service:
sudo service redis-server restart
2. Install and configure TypeScript
Next, we need to install and configure TypeScript. First, make sure you have Node.js and npm installed.
Then, install TypeScript globally with the following command:
npm install -g typescript
Create a new TypeScript project and initialize npm:
mkdir cache-protection cd cache-protection npm init -y
Install the necessary TypeScript dependencies:
npm install redis ioredis express npm install --save-dev @types/redis @types/ioredis @types/express
3. Writing code
Next, we start writing the code for the cache penetration defense function. First, create a file named index.ts in the root directory of the project.
import express, { Request, Response } from 'express'; import Redis from 'ioredis'; const app = express(); const redis = new Redis(); // 缓存查询的函数 async function getDataFromCache(key: string): Promise<string | null> { return await redis.get(key); } // 从数据库查询数据的函数 async function getDataFromDb(key: string): Promise<string | undefined> { // 模拟从数据库查询的过程 const dataFromDb = { '1': 'data1', '2': 'data2', '3': 'data3', }; return dataFromDb[key]; } // 将数据写入缓存的函数 async function setDataToCache(key: string, data: string): Promise<string> { return await redis.set(key, data); } // Express路由处理函数 app.get('/data/:id', async (req: Request, res: Response) => { const dataId = req.params.id; const cacheKey = `data:${dataId}`; // 尝试从缓存中获取数据 let data = await getDataFromCache(cacheKey); // 如果缓存中没有数据,则从数据库中查询并写入缓存 if (!data) { data = await getDataFromDb(dataId); if (data) { await setDataToCache(cacheKey, data); } } // 返回结果 if (data) { res.send(data); } else { res.send('Data not found'); } }); // 启动Express服务 app.listen(3000, () => { console.log('Server is running on port 3000'); });
Code description:
4. Run the code
In the command line, use the following command to compile the TypeScript code into JavaScript:
tsc index.ts
Then, run the compiled JavaScript code:
node index.js
Now, you can test the cache penetration defense function by visiting http://localhost:3000/data/1. The first access will fetch the data from the database and write the data to the cache. Accessing the same URL again will fetch data directly from the cache.
Summary:
This article introduces how to use Redis and TypeScript to develop cache penetration defense functions. Through the combination of cache query functions, data query functions from the database, and data writing cache functions, we can effectively reduce access to the database and improve system performance. At the same time, the high-speed reading and writing features of Redis can better cope with high concurrent access situations.
Hope this article can be helpful to your development work!
The above is the detailed content of How to use Redis and TypeScript to develop cache penetration defense functions. For more information, please follow other related articles on the PHP Chinese website!