@katdev/service-discovery
v1.0.0
Published
Service discovery and registry for microservices
Maintainers
Readme
Service Discovery Package
A simple, in-memory service registry for microservices. Perfect for development and small deployments.
Features
- ✅ Service registration
- ✅ Automatic health checks (heartbeat)
- ✅ Service discovery
- ✅ Load balancing (round-robin)
- ✅ Automatic cleanup of unhealthy instances
- ✅ Easy NestJS integration
Quick Start
1. Install and Build
cd packages/service-discovery
npm install
npm run build2. Use in Your Service
import { Module } from '@nestjs/common';
import { ServiceDiscoveryModule } from '@audit-hub/service-discovery';
@Module({
imports: [ServiceDiscoveryModule],
})
export class AppModule {}3. Register Your Service
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ServiceDiscoveryClientImpl } from '@audit-hub/service-discovery';
@Injectable()
export class MyService implements OnModuleInit, OnModuleDestroy {
private instanceId: string | null = null;
constructor(private readonly discoveryClient: ServiceDiscoveryClientImpl) {}
async onModuleInit() {
// Register this service when it starts
this.instanceId = await this.discoveryClient.registerService('my-service', 3000, 'http');
console.log(`Service registered: ${this.instanceId}`);
}
async onModuleDestroy() {
// Deregister when shutting down
if (this.instanceId) {
await this.discoveryClient.deregisterService(this.instanceId);
}
}
}4. Discover Other Services
// Get URL of another service
const authUrl = await this.discoveryClient.getServiceUrl('auth-service', 'http');
// Get all instances
const instances = await this.discoveryClient.getServiceInstances('auth-service');How It Works
- Registration: Service registers itself when it starts
- Heartbeat: Service sends heartbeat every 10 seconds
- Discovery: Other services can find it by name
- Cleanup: Unhealthy services are automatically removed
Production Note
For production, replace InMemoryServiceRegistry with:
- Consul
- Eureka
- Kubernetes DNS
- etcd
The interface stays the same, just swap the implementation!
