0
# V1 Service Discovery (Synchronous)
1
2
Legacy synchronous API for Nacos service discovery and registration operations. This API provides basic service management functionality using HTTP requests with threading-based operations for backward compatibility.
3
4
## Capabilities
5
6
### Service Instance Registration
7
8
Register service instances with Nacos for service discovery.
9
10
```python { .api }
11
def add_naming_instance(self, service_name: str, ip: str, port: int, cluster_name=None,
12
weight=1.0, metadata=None, ephemeral=True, enabled=True,
13
healthy=True, group_name=None) -> bool:
14
"""
15
Register a service instance.
16
17
Args:
18
service_name (str): Name of the service
19
ip (str): IP address of the instance
20
port (int): Port number of the instance
21
cluster_name (str, optional): Cluster name
22
weight (float): Instance weight for load balancing (default: 1.0)
23
metadata (dict, optional): Instance metadata
24
ephemeral (bool): Whether instance is ephemeral (default: True)
25
enabled (bool): Whether instance is enabled (default: True)
26
healthy (bool): Whether instance is healthy (default: True)
27
group_name (str, optional): Service group name
28
29
Returns:
30
bool: True if registration successful
31
32
Raises:
33
NacosException: If parameters are invalid
34
NacosRequestException: If request fails
35
"""
36
```
37
38
Usage example:
39
40
```python
41
# Basic instance registration
42
client.add_naming_instance("user-service", "192.168.1.100", 8080)
43
44
# Registration with metadata
45
metadata = {
46
"version": "1.0.0",
47
"region": "us-west-1",
48
"zone": "us-west-1a"
49
}
50
client.add_naming_instance(
51
service_name="user-service",
52
ip="192.168.1.100",
53
port=8080,
54
cluster_name="production",
55
weight=1.5,
56
metadata=metadata
57
)
58
59
# Registration with custom group
60
client.add_naming_instance(
61
service_name="user-service",
62
ip="192.168.1.100",
63
port=8080,
64
group_name="microservices"
65
)
66
```
67
68
### Service Instance Deregistration
69
70
Remove service instances from Nacos registry.
71
72
```python { .api }
73
def remove_naming_instance(self, service_name: str, ip: str, port: int, cluster_name=None,
74
ephemeral=True, group_name=None) -> bool:
75
"""
76
Deregister a service instance.
77
78
Args:
79
service_name (str): Name of the service
80
ip (str): IP address of the instance
81
port (int): Port number of the instance
82
cluster_name (str, optional): Cluster name
83
ephemeral (bool): Whether instance is ephemeral (default: True)
84
group_name (str, optional): Service group name
85
86
Returns:
87
bool: True if deregistration successful
88
89
Raises:
90
NacosException: If parameters are invalid
91
NacosRequestException: If request fails
92
"""
93
```
94
95
Usage example:
96
97
```python
98
# Basic instance deregistration
99
client.remove_naming_instance("user-service", "192.168.1.100", 8080)
100
101
# Deregistration from specific cluster
102
client.remove_naming_instance(
103
service_name="user-service",
104
ip="192.168.1.100",
105
port=8080,
106
cluster_name="production"
107
)
108
109
# Deregistration from custom group
110
client.remove_naming_instance(
111
service_name="user-service",
112
ip="192.168.1.100",
113
port=8080,
114
group_name="microservices"
115
)
116
```
117
118
### Service Instance Modification
119
120
Update existing service instance properties.
121
122
```python { .api }
123
def modify_naming_instance(self, service_name: str, ip: str, port: int, cluster_name=None,
124
weight=None, metadata=None, enabled=None, group_name=None) -> bool:
125
"""
126
Modify a service instance.
127
128
Args:
129
service_name (str): Name of the service
130
ip (str): IP address of the instance
131
port (int): Port number of the instance
132
cluster_name (str, optional): Cluster name
133
weight (float, optional): New instance weight
134
metadata (dict, optional): New instance metadata
135
enabled (bool, optional): New enabled status
136
group_name (str, optional): Service group name
137
138
Returns:
139
bool: True if modification successful
140
141
Raises:
142
NacosException: If parameters are invalid
143
NacosRequestException: If request fails
144
"""
145
```
146
147
Usage example:
148
149
```python
150
# Update instance weight
151
client.modify_naming_instance("user-service", "192.168.1.100", 8080, weight=2.0)
152
153
# Update metadata
154
new_metadata = {
155
"version": "1.1.0",
156
"region": "us-west-1",
157
"status": "updated"
158
}
159
client.modify_naming_instance(
160
service_name="user-service",
161
ip="192.168.1.100",
162
port=8080,
163
metadata=new_metadata
164
)
165
166
# Disable instance
167
client.modify_naming_instance("user-service", "192.168.1.100", 8080, enabled=False)
168
```
169
170
### Service Instance Listing
171
172
Retrieve lists of service instances.
173
174
```python { .api }
175
def list_naming_instance(self, service_name: str, clusters=None, namespace_id=None,
176
group_name=None, healthy_only=False) -> list:
177
"""
178
List service instances.
179
180
Args:
181
service_name (str): Name of the service
182
clusters (list, optional): List of cluster names to filter
183
namespace_id (str, optional): Namespace ID
184
group_name (str, optional): Service group name
185
healthy_only (bool): Return only healthy instances (default: False)
186
187
Returns:
188
list: List of service instances
189
190
Raises:
191
NacosException: If parameters are invalid
192
NacosRequestException: If request fails
193
"""
194
```
195
196
Usage example:
197
198
```python
199
# List all instances
200
instances = client.list_naming_instance("user-service")
201
for instance in instances:
202
print(f"Instance: {instance['ip']}:{instance['port']}")
203
204
# List healthy instances only
205
healthy_instances = client.list_naming_instance("user-service", healthy_only=True)
206
207
# List instances from specific clusters
208
instances = client.list_naming_instance(
209
service_name="user-service",
210
clusters=["production", "staging"]
211
)
212
213
# List instances from custom group and namespace
214
instances = client.list_naming_instance(
215
service_name="user-service",
216
namespace_id="production",
217
group_name="microservices"
218
)
219
```
220
221
### Service Instance Querying
222
223
Get detailed information about a specific service instance.
224
225
```python { .api }
226
def get_naming_instance(self, service_name: str, ip: str, port: int, cluster_name=None) -> dict:
227
"""
228
Get detailed information about a specific service instance.
229
230
Args:
231
service_name (str): Name of the service
232
ip (str): IP address of the instance
233
port (int): Port number of the instance
234
cluster_name (str, optional): Cluster name
235
236
Returns:
237
dict: Instance details including metadata, health status, and configuration
238
239
Raises:
240
NacosException: If parameters are invalid
241
NacosRequestException: If request fails
242
"""
243
```
244
245
Usage example:
246
247
```python
248
# Get instance details
249
instance = client.get_naming_instance("user-service", "192.168.1.100", 8080)
250
print(f"Instance details: {instance}")
251
print(f"Health status: {instance.get('healthy', 'unknown')}")
252
print(f"Metadata: {instance.get('metadata', {})}")
253
254
# Get instance from specific cluster
255
instance = client.get_naming_instance(
256
service_name="user-service",
257
ip="192.168.1.100",
258
port=8080,
259
cluster_name="production"
260
)
261
```
262
263
### Health Check and Heartbeat
264
265
Send heartbeat signals to maintain instance health status.
266
267
```python { .api }
268
def send_heartbeat(self, service_name: str, ip: str, port: int, cluster_name=None,
269
weight=1.0, metadata=None, ephemeral=True, group_name=None) -> dict:
270
"""
271
Send heartbeat for a service instance.
272
273
Args:
274
service_name (str): Name of the service
275
ip (str): IP address of the instance
276
port (int): Port number of the instance
277
cluster_name (str, optional): Cluster name
278
weight (float): Instance weight (default: 1.0)
279
metadata (dict, optional): Instance metadata
280
ephemeral (bool): Whether instance is ephemeral (default: True)
281
group_name (str, optional): Service group name
282
283
Returns:
284
dict: Heartbeat response containing server time and other info
285
286
Raises:
287
NacosException: If parameters are invalid
288
NacosRequestException: If request fails
289
"""
290
```
291
292
Usage example:
293
294
```python
295
# Send basic heartbeat
296
response = client.send_heartbeat("user-service", "192.168.1.100", 8080)
297
print(f"Server time: {response.get('clientBeatInterval', 'unknown')}")
298
299
# Send heartbeat with metadata
300
metadata = {"status": "running", "cpu": "20%", "memory": "512MB"}
301
response = client.send_heartbeat(
302
service_name="user-service",
303
ip="192.168.1.100",
304
port=8080,
305
weight=1.5,
306
metadata=metadata
307
)
308
309
# Periodic heartbeat example
310
import time
311
import threading
312
313
def heartbeat_worker():
314
while True:
315
try:
316
client.send_heartbeat("user-service", "192.168.1.100", 8080)
317
time.sleep(5) # Send heartbeat every 5 seconds
318
except Exception as e:
319
print(f"Heartbeat failed: {e}")
320
321
heartbeat_thread = threading.Thread(target=heartbeat_worker, daemon=True)
322
heartbeat_thread.start()
323
```
324
325
### Service Subscription
326
327
Subscribe to service change notifications.
328
329
```python { .api }
330
def subscribe(self, service_name: str, listener_fn, cluster_name=None,
331
group_name=None):
332
"""
333
Subscribe to service changes.
334
335
Args:
336
service_name (str): Name of the service to monitor
337
listener_fn (callable): Callback function for service changes
338
cluster_name (str, optional): Cluster name to monitor
339
group_name (str, optional): Service group name
340
"""
341
342
def unsubscribe(self, service_name: str, listener_fn=None):
343
"""
344
Unsubscribe from service changes.
345
346
Args:
347
service_name (str): Name of the service
348
listener_fn (callable, optional): Listener function to remove (if None, removes all)
349
"""
350
351
def stop_subscribe(self):
352
"""Stop all service subscriptions."""
353
```
354
355
Usage example:
356
357
```python
358
def service_change_handler(event):
359
print(f"Service changed: {event}")
360
# Handle service instance changes
361
instances = event.get('hosts', [])
362
for instance in instances:
363
print(f" Instance: {instance['ip']}:{instance['port']} - {instance['healthy']}")
364
365
# Subscribe to service changes
366
client.subscribe(
367
service_name="user-service",
368
listener_fn=service_change_handler
369
)
370
371
# Subscribe to specific cluster
372
client.subscribe(
373
service_name="user-service",
374
listener_fn=service_change_handler,
375
cluster_name="production"
376
)
377
378
# Subscribe with custom group
379
client.subscribe(
380
service_name="user-service",
381
listener_fn=service_change_handler,
382
group_name="microservices"
383
)
384
385
# Unsubscribe specific listener
386
client.unsubscribe("user-service", service_change_handler)
387
388
# Unsubscribe all listeners for a service
389
client.unsubscribe("user-service")
390
391
# Stop all subscriptions
392
client.stop_subscribe()
393
```
394
395
## Data Structures
396
397
Service instance responses typically contain:
398
399
```python
400
# Example instance data structure
401
{
402
"instanceId": "192.168.1.100#8080#DEFAULT#user-service",
403
"ip": "192.168.1.100",
404
"port": 8080,
405
"weight": 1.0,
406
"healthy": True,
407
"enabled": True,
408
"ephemeral": True,
409
"clusterName": "DEFAULT",
410
"serviceName": "user-service",
411
"metadata": {
412
"version": "1.0.0",
413
"region": "us-west-1"
414
}
415
}
416
417
# Example service change event structure
418
{
419
"name": "user-service",
420
"groupName": "DEFAULT_GROUP",
421
"clusters": "DEFAULT",
422
"cacheMillis": 10000,
423
"hosts": [
424
{
425
"instanceId": "192.168.1.100#8080#DEFAULT#user-service",
426
"ip": "192.168.1.100",
427
"port": 8080,
428
"weight": 1.0,
429
"healthy": True,
430
"enabled": True,
431
"ephemeral": True,
432
"clusterName": "DEFAULT",
433
"serviceName": "user-service",
434
"metadata": {}
435
}
436
],
437
"lastRefTime": 1640995200000,
438
"checksum": "abc123",
439
"allIPs": False,
440
"reachProtectionThreshold": False
441
}
442
```