Reputation: 43
I'm creating Grpc microservices with nestjs. How can i connect both servers on my localhost.
I have tried using ngrok to create a tunnel for one of the service but i'm still getting errors "address in use" and "No address added out of total 2 resolved" even though both are running on different ports
first service
import { authServiceOptions } from './auth/grpc/auth.options';
import { notificationClientServiceOptions } from '../../notification/src/notification/grpc/notification.options';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.setGlobalPrefix('api/v1/services');
// Services
app.connectMicroservice(notificationClientServiceOptions);
app.connectMicroservice(authServiceOptions);
await app.startAllMicroservicesAsync();
await app.listen(51700);
}
bootstrap();
second service
import { AppModule } from './app.module';
import { notificationServiceOptions } from './notification/grpc/notification.options';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.setGlobalPrefix('api/v1/services');
// Services
app.connectMicroservice(notificationServiceOptions);
await app.startAllMicroservicesAsync();
await app.listen(3001);
}
bootstrap();
// client options for second service
export const notificationClientServiceOptions: ClientOptions = {
transport: Transport.GRPC,
options: {
url: 'https://b6a4cd09.ngrok.io/',
package: 'notification',
protoPath: join(__dirname, './notification.proto'),
},
};
Upvotes: 2
Views: 4548
Reputation: 43
Figured it out! Turns out i was specifying a http url for a Grpc service. This is the correct client option for the second service.
export const notificationClientServiceOptions: ClientOptions = {
transport: Transport.GRPC,
options: {
// you can specify any port that is not in use (just don't prefix it with 'http')
url: 'localhost:5500',
package: 'notification',
protoPath: join(__dirname, './notification.proto'),
},
};
Also i looked up into the source code for nestjs. Turns out the default url for any microservice is localhost:5000 hence if your are running more than one service it's best to specify the url for each service.
Another problem i ran into was connecting the microservices;
If the services are located in two separate nestjs projects you don't need to use app.connectMicroservice(secondServiceOptions)
in the firstService
this is because await app.startAllMicroservicesAsync()
would attempt to start both services but it'll fail. This is because the secondService
is already running in a separate project.
To connect to the secondService
from the firstService
use the @Client(secondServiceOptions)
decorator.
Upvotes: 2