我正在学习 Fastify 并像这样使用 @fastify/redis 注册插件
app.register(redisPlugin, {
client: initRedis(app.config.REDIS_INTERNAL__HOST, app.config.REDIS_INTERNAL__PASS),
closeClient: true,
});
并登记路线:
import { FastifyInstance, FastifyPluginAsync } from "fastify";
import v1Routes from "./v1/index.js";
const routes: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
fastify.register(v1Routes, { prefix: "/v1" });
};
export default routes;
以及v1内部路线
const v1Routes: FastifyPluginAsync = async (fastify: FastifyInstance): Promise<void> => {
fastify.register(seedlogsRoutes, { prefix: "/seedlogs" });
};
带控制器的路线
const orderRoutes: FastifyPluginAsync = async (fastify: FastifyInstance) => {
fastify.get("/", getOrders);
};
export default orderRoutes;
使用 getOrders 函数,我可以像这样访问redis:
const getOrders = async (request: FastifyRequest, reply: FastifyReply) => {
const redis = request.server.redis;
await redis.set("orders", "abc");
const orders = await redis.get("orders");
return { message: "Orders", orders };
};
但是如果我想从内部服务访问redis怎么办? FastifyInstance,比如
const cacheOrder = async (order) => {
await redis.set("order",order)
}
我应该在将客户端传递给插件之前初始化客户端并在无法访问 FastifyInstance 的地方重用它吗?
import redis from "./cache/redis.js"
我尝试在Google上搜索,但仍然找不到满意的答案。任何评论表示赞赏。非常感谢。
我应该在将客户端传递给插件之前初始化客户端并在无法访问 FastifyInstance 的地方重用它吗?
不,否则你将拥有像枪一样的全球客户。您需要传播附加到 Fastify 服务器的 Redis 客户端。
这段代码可以简化:
async function getOrders (request: FastifyRequest, reply: FastifyReply) {
// in a named function, `this` is the Fastify server
const redis = this.redis;
await redis.set("orders", "abc");
const orders = await redis.get("orders");
return { message: "Orders", orders };
};
如何从FastifyInstance访问redis
确保拥有 正确的
server
实例,它几乎在以下任何地方都绑定到 this
:
handler(request,reply):处理该请求的函数。当调用处理程序时,Fastify 服务器将绑定到此。注意:使用箭头函数会破坏 this 的绑定。
文档参考:https://fastify.dev/docs/latest/Reference/Routes/#routes-options
有用的阅读:https://backend.cafe/the-complete-guide-to-the-fastify-plugin-system