or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

administrative-operations.mdclient-management.mdconstants-enums.mdexception-handling.mdindex.mdmessage-operations.mdmessage-types.mdsession-management.md

client-management.mddocs/

0

# Client Management

1

2

Core client functionality for establishing connections to Azure Service Bus and creating messaging components. Provides connection string parsing, credential management, and factory methods for senders and receivers.

3

4

## Capabilities

5

6

### ServiceBusClient Initialization

7

8

Creates the main Service Bus client with connection credentials and configuration options.

9

10

```python { .api }

11

class ServiceBusClient:

12

def __init__(

13

self,

14

fully_qualified_namespace: str,

15

credential: Union[TokenCredential, AzureSasCredential, AzureNamedKeyCredential],

16

*,

17

retry_total: int = 3,

18

retry_backoff_factor: float = 0.8,

19

retry_backoff_max: float = 120,

20

retry_mode: str = "exponential",

21

**kwargs

22

):

23

"""

24

Create a Service Bus client.

25

26

Parameters:

27

- fully_qualified_namespace: The fully qualified Service Bus namespace URL

28

- credential: Authentication credential

29

- retry_total: Maximum number of retry attempts

30

- retry_backoff_factor: Backoff factor for retry delays

31

- retry_backoff_max: Maximum backoff time in seconds

32

- retry_mode: Retry strategy ("exponential" or "fixed")

33

"""

34

```

35

36

#### Usage Example

37

38

```python

39

from azure.servicebus import ServiceBusClient

40

from azure.identity import DefaultAzureCredential

41

42

# Using Azure Active Directory credential

43

credential = DefaultAzureCredential()

44

client = ServiceBusClient(

45

fully_qualified_namespace="myservicebus.servicebus.windows.net",

46

credential=credential

47

)

48

49

# Using connection string (easier for development)

50

client = ServiceBusClient.from_connection_string(

51

"Endpoint=sb://myservicebus.servicebus.windows.net/;SharedAccessKeyName=..."

52

)

53

```

54

55

### Connection String Factory

56

57

Creates a ServiceBusClient instance from a connection string with automatic credential parsing.

58

59

```python { .api }

60

@classmethod

61

def from_connection_string(

62

cls,

63

conn_str: str,

64

**kwargs

65

) -> ServiceBusClient:

66

"""

67

Create a Service Bus client from a connection string.

68

69

Parameters:

70

- conn_str: Service Bus connection string

71

- **kwargs: Additional configuration options

72

73

Returns:

74

ServiceBusClient instance

75

"""

76

```

77

78

### Client Properties

79

80

Access to client configuration and connection information.

81

82

```python { .api }

83

@property

84

def fully_qualified_namespace(self) -> str:

85

"""The fully qualified namespace URL of the Service Bus."""

86

```

87

88

### Sender Factory Methods

89

90

Create message senders for queues and topics with configuration options.

91

92

```python { .api }

93

def get_queue_sender(

94

self,

95

queue_name: str,

96

*,

97

client_identifier: Optional[str] = None,

98

socket_timeout: Optional[float] = None,

99

**kwargs

100

) -> ServiceBusSender:

101

"""

102

Create a sender for a specific queue.

103

104

Parameters:

105

- queue_name: Name of the target queue

106

- client_identifier: Optional identifier for the client connection

107

- socket_timeout: Socket timeout in seconds

108

109

Returns:

110

ServiceBusSender instance for the specified queue

111

"""

112

113

def get_topic_sender(

114

self,

115

topic_name: str,

116

*,

117

client_identifier: Optional[str] = None,

118

socket_timeout: Optional[float] = None,

119

**kwargs

120

) -> ServiceBusSender:

121

"""

122

Create a sender for a specific topic.

123

124

Parameters:

125

- topic_name: Name of the target topic

126

- client_identifier: Optional identifier for the client connection

127

- socket_timeout: Socket timeout in seconds

128

129

Returns:

130

ServiceBusSender instance for the specified topic

131

"""

132

```

133

134

### Receiver Factory Methods

135

136

Create message receivers for queues and subscriptions with extensive configuration options.

137

138

```python { .api }

139

def get_queue_receiver(

140

self,

141

queue_name: str,

142

*,

143

client_identifier: Optional[str] = None,

144

socket_timeout: Optional[float] = None,

145

session_id: Optional[Union[str, NextAvailableSessionType]] = None,

146

sub_queue: Optional[Union[ServiceBusSubQueue, str]] = None,

147

receive_mode: Union[ServiceBusReceiveMode, str] = ServiceBusReceiveMode.PEEK_LOCK,

148

max_wait_time: Optional[float] = None,

149

auto_lock_renewer: Optional[AutoLockRenewer] = None,

150

prefetch_count: int = 0,

151

**kwargs

152

) -> ServiceBusReceiver:

153

"""

154

Create a receiver for a specific queue.

155

156

Parameters:

157

- queue_name: Name of the source queue

158

- client_identifier: Optional identifier for the client connection

159

- socket_timeout: Socket timeout in seconds

160

- session_id: Session ID for session-enabled queues, or NEXT_AVAILABLE_SESSION

161

- sub_queue: Sub-queue type (DEAD_LETTER, TRANSFER_DEAD_LETTER)

162

- receive_mode: Message receive mode (PEEK_LOCK or RECEIVE_AND_DELETE)

163

- max_wait_time: Maximum time to wait for messages

164

- auto_lock_renewer: AutoLockRenewer instance for automatic lock renewal

165

- prefetch_count: Number of messages to prefetch (0 disables prefetching)

166

167

Returns:

168

ServiceBusReceiver instance for the specified queue

169

"""

170

171

def get_subscription_receiver(

172

self,

173

topic_name: str,

174

subscription_name: str,

175

*,

176

client_identifier: Optional[str] = None,

177

socket_timeout: Optional[float] = None,

178

session_id: Optional[Union[str, NextAvailableSessionType]] = None,

179

sub_queue: Optional[Union[ServiceBusSubQueue, str]] = None,

180

receive_mode: Union[ServiceBusReceiveMode, str] = ServiceBusReceiveMode.PEEK_LOCK,

181

max_wait_time: Optional[float] = None,

182

auto_lock_renewer: Optional[AutoLockRenewer] = None,

183

prefetch_count: int = 0,

184

**kwargs

185

) -> ServiceBusReceiver:

186

"""

187

Create a receiver for a specific subscription.

188

189

Parameters:

190

- topic_name: Name of the source topic

191

- subscription_name: Name of the subscription

192

- client_identifier: Optional identifier for the client connection

193

- socket_timeout: Socket timeout in seconds

194

- session_id: Session ID for session-enabled subscriptions, or NEXT_AVAILABLE_SESSION

195

- sub_queue: Sub-queue type (DEAD_LETTER, TRANSFER_DEAD_LETTER)

196

- receive_mode: Message receive mode (PEEK_LOCK or RECEIVE_AND_DELETE)

197

- max_wait_time: Maximum time to wait for messages

198

- auto_lock_renewer: AutoLockRenewer instance for automatic lock renewal

199

- prefetch_count: Number of messages to prefetch (0 disables prefetching)

200

201

Returns:

202

ServiceBusReceiver instance for the specified subscription

203

"""

204

```

205

206

#### Usage Example

207

208

```python

209

from azure.servicebus import ServiceBusClient, ServiceBusReceiveMode, NEXT_AVAILABLE_SESSION

210

211

client = ServiceBusClient.from_connection_string("your_connection_string")

212

213

# Create a basic queue receiver

214

receiver = client.get_queue_receiver("my-queue")

215

216

# Create a session-enabled queue receiver for next available session

217

session_receiver = client.get_queue_receiver(

218

"my-session-queue",

219

session_id=NEXT_AVAILABLE_SESSION

220

)

221

222

# Create a subscription receiver with custom configuration

223

subscription_receiver = client.get_subscription_receiver(

224

topic_name="my-topic",

225

subscription_name="my-subscription",

226

receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE,

227

prefetch_count=10

228

)

229

```

230

231

### Resource Management

232

233

Properly close client connections and release resources.

234

235

```python { .api }

236

def close(self) -> None:

237

"""

238

Close the client and release all associated resources.

239

240

This should be called when the client is no longer needed to ensure

241

proper cleanup of network connections and other resources.

242

"""

243

```

244

245

### Context Manager Support

246

247

ServiceBusClient supports context manager protocol for automatic resource cleanup.

248

249

```python { .api }

250

def __enter__(self) -> ServiceBusClient: ...

251

def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...

252

```

253

254

#### Usage Example

255

256

```python

257

# Automatic resource cleanup with context manager

258

with ServiceBusClient.from_connection_string("your_connection_string") as client:

259

with client.get_queue_sender("my-queue") as sender:

260

sender.send_messages(ServiceBusMessage("Hello"))

261

262

with client.get_queue_receiver("my-queue") as receiver:

263

messages = receiver.receive_messages(max_message_count=5)

264

for message in messages:

265

receiver.complete_message(message)

266

# Client and all senders/receivers are automatically closed

267

```

268

269

### Connection String Parsing Utilities

270

271

Parse and work with Service Bus connection strings directly.

272

273

```python { .api }

274

def parse_connection_string(conn_str: str) -> ServiceBusConnectionStringProperties:

275

"""

276

Parse a Service Bus connection string into its components.

277

278

Parameters:

279

- conn_str: Service Bus connection string

280

281

Returns:

282

ServiceBusConnectionStringProperties with parsed components

283

"""

284

285

class ServiceBusConnectionStringProperties:

286

"""Parsed components of a Service Bus connection string."""

287

@property

288

def endpoint(self) -> str: ...

289

@property

290

def entity_path(self) -> Optional[str]: ...

291

@property

292

def shared_access_key_name(self) -> Optional[str]: ...

293

@property

294

def shared_access_key(self) -> Optional[str]: ...

295

@property

296

def shared_access_signature(self) -> Optional[str]: ...

297

```

298

299

## Asynchronous Client Management

300

301

For asynchronous operations, use the async version of ServiceBusClient from the `azure.servicebus.aio` module.

302

303

```python { .api }

304

from azure.servicebus.aio import ServiceBusClient

305

306

class ServiceBusClient:

307

# Same methods as sync version but with async/await

308

async def __aenter__(self) -> ServiceBusClient: ...

309

async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...

310

async def close(self) -> None: ...

311

```

312

313

#### Usage Example

314

315

```python

316

import asyncio

317

from azure.servicebus.aio import ServiceBusClient

318

from azure.servicebus import ServiceBusMessage

319

320

async def main():

321

async with ServiceBusClient.from_connection_string("your_connection_string") as client:

322

async with client.get_queue_sender("my-queue") as sender:

323

await sender.send_messages(ServiceBusMessage("Hello Async"))

324

325

async with client.get_queue_receiver("my-queue") as receiver:

326

messages = await receiver.receive_messages(max_message_count=5)

327

for message in messages:

328

await receiver.complete_message(message)

329

330

asyncio.run(main())

331

```