Redis
There is another way to work with Nest microservices. Instead of direct TCP communication, we could use amazing Redis feature - publish / subscribe.
还有另外一种与Nest 微服务的通信方式。我们可以使用强大的Redis功能publish
/ subscribe
代替直接TCP通信。
Of course before you can use it, it is obligatory to install Redis.
当然,必须安装Redis之后才能使用。
创建微服务
To create Redis Microservice, you have to pass additional configuration in NestFactory.createMicroservice() method.
要创建Redis微服务就必须在NestFactory.createMicroservice()
方法中传递其他配置。
const app = NestFactory.createMicroservice(
MicroserviceModule,
{
transport: Transport.REDIS,
url: 'redis://localhost:6379'
}
);
app.listen(() => console.log('Microservice listen on port:', 5667 ));
And that's all. Now your microservice will subscribe to messages published via Redis. The rest works same - patterns, error handling, etc.
好了,现在你创建的微服务可以订阅通过Redis发布的消息了。其他的步骤与TCP相同--模式,异常处理等。
客户端
Now, let's see how to create client. Previously, your client instance configuration looks like that:
现在,让我们来创建客户端。在使用TCP时,你的客户端实例配置如下:
@Client({ transport: Transport.TCP, port: 5667 })
client: ClientProxy;
We want to use Redis instead of TCP, so we have to change those settings:
我们使用Redis代替TCP,所以我们应该更改这些设置:
@Client({ transport: Transport.REDIS, url: 'redis://localhost:6379' })
client: ClientProxy;
Easy, right? That's all. Other functionalities works same as in TCP communication.
是不是很简单?其他功能与TCP通信相同。