1

如何在 server.js 中声明 redis 连接时使用来自其他控制器或 other.js 的 fastify-redis 插件

服务器.js

const fastify = require('fastify')({ logger: false })
const routes = require('./routes')

fastify.register(require('fastify-redis'), { host: '127.0.0.1' })

routes.forEach((route, index) => {
    fastify.route(route)
})

const start = async () => {
    try {
        await fastify.listen(3000)
        fastify.log.info(`server listening on ${fastify.server.address().port}`)
        //const { redis } = fastify
        //console.log(redis)
    } catch (err) {
        fastify.log.error(err)
        process.exit(1)
    }
}
start()

控制器 -> books.js

exports.getBooks = async (request, reply) => {

    //console.log(redis)
    let data = {
        book: 'Book 1',
        author: 'Author 1'
    }

    //return data
    return redis.get('key1') // Not Defined
    //return redis.get('key1')
}

那么,简单来说,我如何使用其他文件中的 Redis 实例来设置 Redis 中的一些值来实现缓存数据库数据。

4

3 回答 3

3

If you write your handler with a simple function (aka no arrow function), the this object will be binded to the fastify server:

exports.getBooks = async function (request, reply) {
    console.log(this)
    let data = {
        book: 'Book 1',
        author: 'Author 1'
    }
    return this.redis.get('key1')
}
于 2020-02-06T07:46:55.967 回答
0

在调用 .after() 时发送 fastify 的实例,decorateRequest然后你就可以在路由处理程序中 redis调用时使用。request

于 2020-07-02T18:19:42.990 回答
0

我会做这样的事情:基本上将app实例传递给用于引导路由的路由中的导出函数。

在路线中

module.exports = fastify => [
    {
        url: '/hello',
        method: 'GET',
        handler: async (request, reply) => {
            const { redis } = fastify
            // ...
        }
    },
    {
        url: '/hello',
        method: 'POST',
        handler: async (request, reply) => {
            const { redis } = fastify
            // ...
        }
    }
]

并在开始时引导路线

app.register(plugin1)
    .register(plugin2)
    .after(() => {
        // bootstraping routes
        // route definition should either be done as a plugin or within .after() callback
        glob.sync(`${__dirname}/routes/*.js`, { cwd: __dirname })
            .map(f => path.resolve(__dirname, f))
            .forEach(file => {
                const routeConfigs = require(file)(app)
                for (let i = 0; i < routeConfigs.length; i += 1) {
                    const routeConfig = routeConfigs[i]
                    app.route(routeConfig)
                }
            })
    })
于 2019-12-25T01:54:18.997 回答