redis使用api_如何使用Redis增强Web API

redis使用api

Performance is an essential parameter to consider when you're designing any piece of software. It is particularly important when it comes to what happens behind-the-scenes.

在设计任何软件时,性能都是要考虑的基本参数。 对于幕后发生的事情,这尤其重要。

We, as developers and technologists, adopt multiple tweaks and implementations in order to improve performance. This is where caching comes into play.

作为开发人员和技术人员,我们采取了多种调整和实施措施以提高性能。 这是缓存起作用的地方。

Caching is defined as a mechanism to store data or files in a temporary storage location from where it can be instantly accessed whenever required.
高速缓存定义为一种将数据或文件存储在临时存储位置的机制,可以从该位置在需要时立即对其进行访问。

Caching has become a must have in web applications nowadays. We can use Redis to supercharge our web APIs - which are built using Node.js and MongoDB.

如今,缓存已成为Web应用程序中的必备功能。 我们可以使用Redis增强我们的Web API,这些Web API是使用Node.js和MongoDB构建的。

Redis:Layman的概述 (Redis: A Layman's Overview )

Redis, according to the official documentation, is defined as an in-memory data structure store which is used as a database, message broker, or cache storage. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.

根据官方文档, Redis被定义为内存中的数据结构存储,用作数据库,消息代理或缓存存储。 它支持数据结构,例如字符串,哈希,列表,集合,带范围查询的排序集合,位图,超日志,带有半径查询和流的地理空间索引。

Okay, that is quite a lot of data structures right there. Just to make it simple, almost all the data structures supported can be condensed into one form of string or the other. You will get more clarity as we run through the implementation.

好的,那儿有很多数据结构。 为了简单起见,几乎所有支持的数据结构都可以压缩为一种字符串形式或另一种形式。 在我们执行实施过程中,您将更加清楚。

But one thing is clear. Redis is powerful, and when used properly can make our applications not only faster but amazingly efficient. Enough talk. Let's get our hands dirty.

但是有一件事很清楚。 Redis功能强大,如果使用得当,可以使我们的应用程序不仅速度更快,而且效率惊人。 聊够了。 让我们弄脏双手。

让我们来谈谈代码 (Let's Talk Code)

Before we start off, you will need to get redis setup in your local system. You can follow this quick setup process to get redis up and running.

在我们开始之前,您将需要在本地系统中进行Redis设置。 您可以按照此快速设置过程来启动和运行Redis。

Done? Cool. Let's start. We have a simple application created in Express which makes use of an instance in MongoDB Atlas to read and write data from.

做完了吗 凉。 开始吧。 我们在Express中创建了一个简单的应用程序,该应用程序使用MongoDB Atlas中的实例来读取和写入数据。

We have two major APIs created in the /blogs route file.

我们在/blogs路由文件中创建了两个主要的API。

撒一些Redis善良 (Sprinkling Some Redis Goodness)

We start off by downloading the npm package redis to connect to the local redis server.

我们首先下载npm包redis以连接到本地redis服务器。

We make use of the utils.promisify function to transform the client.hget function to return a promise instead of a callback. You can read more about promisification here.

我们利用utils.promisify函数来转换client.hget函数以返回promise,而不是回调。 您可以在这里阅读更多关于promisification 信息

The Redis connection is in place. Before we start writing any more caching code, let us take a step back and try to understand what are the requirements we need to fulfill and the likely challenges we might face.

Redis连接到位。 在我们开始编写更多的缓存代码之前,让我们退后一步,尝试了解我们需要满足哪些要求以及可能面临的挑战。

Our caching strategy should be able to address the following points.

我们的缓存策略应该能够解决以下几点。

  • Cache the request for all blog posts for a particular user

    缓存对特定用户的所有博客帖子的请求
  • Clear cache every time a new blog post is created

    每次创建新博客帖子时清除缓存

The likely challenges we should be careful of as we go about our strategy are:

我们在执行策略时应注意的可能挑战是:

  • The right way to handle key creation for storing cache data

    处理存储高速缓存数据的密钥创建的正确方法
  • Cache expiration logic and forced expiration for maintaining cache freshness

    高速缓存过期逻辑和强制过期以保持高速缓存的新鲜度
  • Reusable implementation of caching logic

    缓存逻辑的可重用实现

All right. We have our points jotted down and redis connected. On to the next step.

行。 记下了点数,并重新连接了Redis。 继续下一步。

覆盖默认的Mongoose Exec函数 (Overriding the Default Mongoose Exec Function)

We want our caching logic to be reusable. And not only reusable, we also want it to be the first checkpoint before we make any query to the database. This can easily be done by using a simple hack of piggy-backing onto the mongoose exec function.

我们希望我们的缓存逻辑是可重用的。 而且不仅可重用,我们还希望它成为对数据库进行任何查询之前的第一个检查点。 这可以通过使用简单的of带到mongoose exec函数上来轻松完成。

We make use of the prototype object of mongoose to add our caching logic code as the first execution in the query.

我们使用猫鼬的原型对象将缓存逻辑代码添加为查询中的第一个执行。

将缓存添加为查询 (Adding Cache as a Query)

In order to denote which queries should be up for caching, we create a mongoose query. We provide the ability to pass the user to be used as a hash-key through the options object.

为了表示哪些查询应该进行缓存,我们创建了一个猫鼬查询。 我们提供了通过options对象将user用作哈希键的options

Note: Hashkey serves as an identifier for a hash data structure which, in layman terms, can be stated as the parent key to a set of key-value pairs. Thereby, enabling caching of a larger number of query-value set. You can read more about hashes in redis here.

注意: Hashkey用作哈希数据结构的标识符,以通俗易懂的方式,可以将其表示为一组键值对的父键。 由此,能够缓存更多的查询值集。 您可以在此处阅读有关redis哈希的更多信息。

Having done so, we can easily use the cache(<options argument>) query along with the queries we want to cache in the following manner.

这样做后,我们可以通过以下方式轻松地将cache(<options argument>)查询与我们要缓存的查询一起使用。

制作缓存逻辑 (Crafting The Cache Logic)

We have set up a common reusable query to denote which queries need to be cached. Let's go ahead and write the central caching logic.

我们建立了一个通用的可重用查询,以表示需要缓存哪些查询。 让我们继续编写中央缓存逻辑。

Whenever we use the cache() query along with our main query, we set the enableCache key to be true.

每当我们将cache()查询与主查询一起使用时,我们都将enableCache键设置为true。

If the key is false, we return the main exec query as default. If not, we first form the key for fetching and storing/refreshing the cache data.

如果键为假,则默认返回主exec查询。 如果不是,我们首先形成用于获取和存储/刷新缓存数据的密钥。

We use the collection name along with the default query as the key name for the sake of uniqueness. The hash-key used is the name of the user which we have already set earlier in the cache() function definition.

为了唯一,我们将collection名称和默认查询一起用作键名称。 所使用的哈希键是我们先前已在cache()函数定义中设置的user名。

The cached data is fetched using the client.hget() function which requires the hash-key and the consequent key as parameters.

使用client.hget()函数获取缓存的数据,该函数需要哈希键和后续键作为参数。

Note: We always use JSON.parse() while fetching any data from redis. And similarly, we use JSON.stringify() on the key and data before storing anything into redis. This is done since redis does not support JSON data structures.

注意:在从redis获取任何数据时,我们总是使用JSON.parse() 。 同样,在将任何内容存储到redis之前,我们在键和数据上使用JSON.stringify() 。 这样做是因为redis不支持JSON数据结构。

Once we have obtained the cached data, we have to transform each of the cached objects into a mongoose model. This can be done by simply using new this.model(<object>).

一旦获得了缓存的数据,就必须将每个缓存的对象转换为猫鼬模型。 这可以通过简单地使用new this.model(<object>)

If the cache does not contain the required data, we make a query to the database. Then, having returned the data to the API, we refresh the cache using client.hmset(). We also set a default cache expiration time of 300 seconds. This is customizable based on your caching strategy.

如果缓存不包含必需的数据,我们将查询数据库。 然后,将数据返回给API后,我们使用client.hmset()刷新缓存。 我们还将默认缓存过期时间设置为300秒。 可根据您的缓存策略进行自定义。

The caching logic is in place. We have also set a default expiration time. Next up, we look at forcing cache expiration whenever a new blog post is created.

缓存逻辑到位。 我们还设置了默认的过期时间。 接下来,我们研究每当创建新博客文章时强制缓存过期。

强制缓存过期 (Forced Cache Expiration)

In certain cases, such as when a user creates a new blog post, the user expects that the new post should be available when they fetche all the posts.

在某些情况下,例如当用户创建新博客帖子时,用户希望在获取所有帖子时该新帖子应该可用。

In order to do so, we have to clear the cache related to that user and update it with new data. So we have to force expiration. We can do that by invoking the del() function provided by redis.

为此,我们必须清除与该用户相关的缓存,并使用新数据对其进行更新。 因此,我们必须强制到期。 我们可以通过调用redis提供的del()函数来实现。

We also have to keep in mind that we will be forcing expiration on multiple routes. One extensible way is to use this clearCache() as a middleware and call it once any query related to a route has finished execution.

我们还必须记住,我们将迫使多条路线到期。 一种可扩展的方法是将此clearCache()用作中间件,并在与路由有关的任何查询完成执行后调用它。

This middleware can be easily called on a particular route in the following way.

可以通过以下方式在特定路径上轻松调用此中间件。

And we are done. I agree that was a quite a lot of code. But with that last part, we have set up redis with our application and taken care of almost all the likely challenges. It is time to see our caching strategy in action.

我们完成了。 我同意这是很多代码。 但是在最后一部分中,我们已经在应用程序中设置了redis并解决了几乎所有可能的挑战。 现在是时候看看我们的缓存策略了。

Redis在行动 (Redis in Action)

We make use of Postman as the API client to see our caching strategy in action. Here we go. Let's run through the API operations, one by one.

我们将Postman用作API客户端,以了解我们的缓存策略的实际应用。 开始了。 让我们一步一步地进行API操作。

  1. We create a new blog post using the /blogs route

    我们使用/blogs路由创建一个新的博客文章

2. We then fetch all the blog posts related to user tejaz

2.然后,获取与用户tejaz相关的所有博客文章。

3. We fetch all the blog posts for user tejaz once more.

3.我们再次获取用户tejaz所有博客文章。

You can clearly see that when we fetch from the cache, the time taken has gone down from 409ms to 24ms. This supercharges your API by decreasing the time taken by almost 95%.

您可以清楚地看到,当我们从缓存中获取数据时,所花费的时间从409ms减少24ms 。 这样可以减少将近95%的时间,从而为您的API增光添彩

Plus, we can clearly see that cache expiration and update operations work as expected.

另外,我们可以清楚地看到缓存过期和更新操作可以按预期进行。

You can find the complete source code in the redis-express folder here.

您可以在此处的redis-express文件夹中找到完整的源代码。

结论 (Conclusion)

Caching is a mandatory step for any performance-efficient and data-intensive application. Redis helps you easily achieve this in your web applications. It is a super powerful tool, and if used properly it can definitely provide an excellent experience to developers as well as users all around.

对于任何性能高效且数据密集的应用程序,缓存都是必不可少的步骤。 Redis帮助您在Web应用程序中轻松实现这一目标。 它是一个超级强大的工具,如果使用得当,它无疑可以为开发人员和周围的用户提供出色的体验。

You can find the complete set of redis commands here. You can use it with redis-cli to monitor your cache data and application processes.

您可以在此处找到完整的redis命令集。 您可以将它与redis-cli一起使用,以监视缓存数据和应用程序进程。

The possibilities offered by any particular technology is truly endless. If you have any queries, you can reach out to me on LinkedIn.

任何特定技术提供的可能性确实是无止境的。 如果您有任何疑问,可以在LinkedIn上与我联系。

In the mean time, keep coding.

同时,继续编码。

翻译自: https://www.freecodecamp.org/news/redis-caching-essentials-with-node-and-mongoose/

redis使用api

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值