Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork37
Plugin to share a common Redis connection across Fastify
License
fastify/fastify-redis
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Fastify Redis connection plugin; with this you can share the same Redis connection in every part of your server.
npm i @fastify/redis
Plugin version | Fastify version |
---|---|
>=7.x | ^5.x |
^6.x | ^4.x |
>=4.x <6.x | ^3.x |
^3.x | ^2.x |
>=1.x <3.x | ^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this pluginin the table above.SeeFastify's LTS policy for more details.
Add it to your project withregister
and you are done!
Under the hoodioredis is used as client, theoptions
that you pass toregister
will be passed to the Redis client.
constfastify=require('fastify')()// create by specifying hostfastify.register(require('@fastify/redis'),{host:'127.0.0.1'})// OR by specifying Redis URLfastify.register(require('@fastify/redis'),{url:'redis://127.0.0.1',/* other redis options */})// OR with more optionsfastify.register(require('@fastify/redis'),{host:'127.0.0.1',password:'***',port:6379,// Redis portfamily:4// 4 (IPv4) or 6 (IPv6)})
Once you have registered your plugin, you can access the Redis client viafastify.redis
.
The client is automatically closed when the fastify instance is closed.
'use strict'constFastify=require('fastify')constfastifyRedis=require('@fastify/redis')constfastify=Fastify({logger:true})fastify.register(fastifyRedis,{host:'127.0.0.1',password:'your strong password here',port:6379,// Redis portfamily:4// 4 (IPv4) or 6 (IPv6)})fastify.get('/foo',(req,reply)=>{const{ redis}=fastifyredis.get(req.query.key,(err,val)=>{reply.send(err||val)})})fastify.post('/foo',(req,reply)=>{const{ redis}=fastifyredis.set(req.body.key,req.body.value,(err)=>{reply.send(err||{status:'ok'})})})fastify.listen({port:3000},err=>{if(err)throwerrconsole.log(`server listening on${fastify.server.address().port}`)})
You may also supply an existingRedis client instance by passing an optionsobject with theclient
property set to the instance. In this case,the client is not automatically closed when the Fastify instance isclosed.
'use strict'constfastify=require('fastify')()constRedis=require('ioredis')constclient=newRedis({host:'localhost',port:6379})fastify.register(require('@fastify/redis'),{ client})
You can also supply aRedis Cluster instance to the client:
'use strict'constfastify=require('fastify')()constRedis=require('ioredis')constclient=newRedis.Cluster([{host:'localhost',port:6379}]);fastify.register(require('@fastify/redis'),{ client})
Note: by default,@fastify/redis willnot automatically close the clientconnection when the Fastify server shuts down.
To automatically close the client connection, set clientClose to true.
fastify.register(require('@fastify/redis'),{ client,closeClient:true})
By using thenamespace
option you can register multiple Redis client instances.
'use strict'constfastify=require('fastify')()fastify.register(require('@fastify/redis'),{host:'127.0.0.1',port:6380,namespace:'hello'}).register(require('@fastify/redis'),{client:redis,namespace:'world'})// Here we will use the `hello` named instancefastify.get('/hello',(req,reply)=>{const{ redis}=fastifyredis.hello.get(req.query.key,(err,val)=>{reply.send(err||val)})})fastify.post('/hello',(req,reply)=>{const{ redis}=fastifyredis['hello'].set(req.body.key,req.body.value,(err)=>{reply.send(err||{status:'ok'})})})// Here we will use the `world` named instancefastify.get('/world',(req,reply)=>{const{ redis}=fastifyredis['world'].get(req.query.key,(err,val)=>{reply.send(err||val)})})fastify.post('/world',(req,reply)=>{const{ redis}=fastifyredis.world.set(req.body.key,req.body.value,(err)=>{reply.send(err||{status:'ok'})})})fastify.listen({port:3000},function(err){if(err){fastify.log.error(err)process.exit(1)}})
@fastify/redis
supports Redis streams out of the box.
'use strict'constfastify=require('fastify')()fastify.register(require('@fastify/redis'),{host:'127.0.0.1',port:6380})fastify.get('/streams',async(request,reply)=>{// We write an event to the stream 'my awesome fastify stream name', setting 'key' to 'value'awaitfastify.redis.xadd(['my awesome fastify stream name','*','hello','fastify is awesome'])// We read events from the beginning of the stream called 'my awesome fastify stream name'letredisStream=awaitfastify.redis.xread(['STREAMS','my awesome fastify stream name',0])// We parse the resultsletresponse=[]letevents=redisStream[0][1]for(leti=0;i<events.length;i++){conste=events[i]response.push(`#LOG: id is${e[0].toString()}`)// We log each keyfor(constkeyine[1]){response.push(e[1][key].toString())}}reply.status(200)return{output:response}// Will return something like this :// { "output": ["#LOG: id is 1559985742035-0", "hello", "fastify is awesome"] }})fastify.listen({port:3000},function(err){if(err){fastify.log.error(err)process.exit(1)}})
NB you can find more information about Redis streams and the relevant commandshere andhere.
The majority of errors are silent due to theioredis
silent error handling but during the plugin registration it will check that the connection with the redis instance is correctly estabilished.In this case, you can receive anERR_AVVIO_PLUGIN_TIMEOUT
error if the connection cannot be established in the expected time frame or a dedicated error for an invalid connection.
This project is kindly sponsored by:
Licensed underMIT.
About
Plugin to share a common Redis connection across Fastify
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.