I am working with the nestjs project, and I can register my service to consul:
import { Injectable, OnModuleInit } from '@nestjs/common';
import * as Consul from 'consul';
import { ConsulRegistedService } from './consul-service-dto';
@Injectable()
export class ConsulService implements OnModuleInit {
privateconsul;
constructor() {
this.consul=newConsul({
host:'192.168.60.9',
port:8500,
secure:false,
promisify:true,
token:'da9f8637-cab8-f9d6-9792-d0f3abd248f5',
});
}
asynconModuleInit():Promise<void> {
try {
constaddress='192.168.60.234';
constport=3567; // replace this with the actual port your service is listening on
constserviceId=`consulreg-service-${address}-${port}`;
awaitthis.consul.agent.service.register({
id:serviceId,
name:'consulreg-service',
address,
port:parseInt(String(port), 10),
// check: {
// http: `http://${address}:${port}/api/health`,
// interval: '30s',
// deregistercriticalserviceafter: '1m',
// },
});
process.on('SIGINT', async () => {
console.log(
'De-registering the service from Consul before shutting down...',
);
awaitthis.consul.agent.service.deregister(serviceId);
process.exit();
});
} catch (error) {
console.error('Failed to register with Consul', error);
process.exit(1);
}
}
// To Fetch
asyncgetServiceInstances(
serviceName:string,
): Promise<{ address: string; port: number }[]> {
try {
constservices=awaitthis.consul.agent.services();
constss=awaitthis.consul.catalog.service.list();
console.log(services);
constserviceInstances= (
Object.values(services) asConsulRegistedService[]
).filter((service) => service.Service === serviceName);
returnserviceInstances.map((service) => ({
address:service.Address,
port:service.Port,
}));
} catch (error) {
console.error(`Failed to get instances of service ${serviceName}`, error);
return [];
}
}
}
I can use this to register my service. Then I can use getServiceInstances to get the service
{
'consulreg-service-192.168.60.234-3567': {
ID: 'consulreg-service-192.168.60.234-3567',
Service: 'consulreg-service',
Tags: [],
Meta: {},
Port: 3567,
Address: '192.168.60.234',
TaggedAddresses: { lan_ipv4: [Object], wan_ipv4: [Object] },
Weights: { Passing: 1, Warning: 1 },
EnableTagOverride: false,
Datacenter: 'dc1'
}
}
In other services, they can use the address and port to access. this should be the client‑side discovery. however, I want to use the server‑side discovery, how can I use it in my nestjs project?