Class RabbitAdmin
- All Implemented Interfaces:
AutoCloseable
try (RabbitAdmin admin = RabbitAdmin.connect("http://localhost:15672", "guest", "guest")) {
QueueInfo queue = admin.queue("orders.new").orElseThrow();
System.out.println(queue.argument("x-message-ttl"));
}
Port 15672, not 5672, and HTTP rather than AMQP. This is a different protocol to a
different endpoint with different credentials, and it is available only where the
rabbitmq_management plugin is enabled — which is why nothing in the message path may
depend on it.
Every call has a timeout
Not configurable away, only adjustable. A management call is usually made while something else is already wrong — during a deployment, or while somebody is diagnosing an incident — and a request that hangs forever at that moment turns a slow broker into a stuck process.
Absent is not an error
A queue that does not exist comes back as Optional.empty() rather than an
exception, because "is it there?" is the question most callers are asking. A 401 or a
missing plugin is an exception, and says which of the two it was: those are
configuration mistakes, and reporting them as "no queue" would send somebody looking in the
wrong place entirely.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final StringThe default virtual host, which is literally a forward slash. -
Method Summary
Modifier and TypeMethodDescriptionauthAttempts(String node) Login attempts one node has counted, per protocol.authAttemptsBySource(String node) Login attempts one node has counted, per remote address and username.voidBinds an exchange to another exchange.bindings()bindingsForQueue(String queue) What is bound to a queue.voidBinds a queue to an exchange.channels()voidclearUserLimit(String user, String limit) voidclearVhostLimit(String limit) voidclose()voidcloseConnection(String name, String reason) Closes a client connection.static RabbitAdminstatic RabbitAdminconnection(String name) voidcreateUser(String name, String password, String... tags) Creates or updates a user.voidcreateUser(String name, PasswordHash hash, String... tags) Creates or updates a user from a hash computed elsewhere.voidcreateVhost(String name) Creates a virtual host, or does nothing when it is already there.voidvoiddeclareQueue(String name, boolean durable, Map<String, Object> arguments) Declares a queue.voiddeclareShovel(String name, Map<String, Object> definition) Declares a dynamic shovel, or replaces one of the same name.voiddeleteExchange(String name) voidvoiddeleteOperatorPolicy(String name) voiddeletePolicy(String name) voiddeleteQueue(String name) voiddeleteShovel(String name) voiddeleteUser(String name) voiddeleteUsers(String... names) Deletes several users in one request.voiddeleteVhost(String name) Deletes a virtual host and everything in it.Exports everything the broker is configured to be.The links that actually exist.voidGrants a user access to this client's virtual host.voidgrantTopic(String user, String exchange, String write, String read) health()The broker's own health checks.voidimportDefinitions(String json) Applies a definitions document to this broker.nodes()Policies an operator sets and a user cannot override.parameters(String component) Runtime parameters of one component.policies()voidpurgeQueue(String name) Discards every message in a queue, keeping the queue.voidDeclares an upstream, or replaces one of the same name.voidvoidCreates or replaces a policy.Looks a queue up, with the arguments the broker actually holds.queues()voidMoves queue leaders so each node leads a fair share.voidresetAuthAttempts(String node) Zeroes one node's login counters, the per-protocol totals and the per-source entries alike — after a misconfigured client is fixed, say, so a failure that follows is a new one.voidvoidrevokeTopic(String user) voidsetUserLimit(String user, String limit, long value) voidsetVhostLimit(String limit, long value) shovels()Connections over the stream protocol, across all virtual hosts.There is no per-stream form of this, unlikestreamPublishers(String):/api/stream/consumers/{vhost}/{stream}answers 400 on 3.13 and 4.x alike.streamPublishers(String stream) Routing-key authorisation on topic exchanges.toString()voidunbind(BindingInfo binding) Removes a binding.users()Users that cannot reach any virtual host.version()Checks the broker is reachable and the credentials work.vhost()vhosts()whoami()
-
Field Details
-
DEFAULT_VHOST
The default virtual host, which is literally a forward slash.- See Also:
-
-
Method Details
-
connect
- Parameters:
url- the management base URL, for examplehttp://localhost:15672user- a user with themonitoringoradministratortagpassword- its password- Returns:
- a client for the default virtual host
-
connect
- Parameters:
url- the management base URLuser- a user with themonitoringoradministratortagpassword- its passwordtimeout- how long any one call may take- Returns:
- a client for the default virtual host
-
forVhost
- Parameters:
name- a virtual host- Returns:
- a client reading that virtual host instead of
/, sharing this one's endpoint, credentials and timeout
-
queue
Looks a queue up, with the arguments the broker actually holds.- Parameters:
name- the queue's name- Returns:
- the queue, or empty when there is no such queue in this virtual host
-
queues
- Returns:
- every queue in this virtual host
-
version
Checks the broker is reachable and the credentials work.Worth calling at start-up rather than discovering at the first real call, because the three ways this fails — wrong password, plugin absent, wrong port — all produce the same confusion later.
- Returns:
- the broker's reported version
-
exchange
- Parameters:
name- the exchange's name; the empty string is the default exchange- Returns:
- the exchange, or empty when there is no such exchange in this virtual host
-
exchanges
- Returns:
- every exchange in this virtual host, including the broker's own
-
bindings
- Returns:
- every binding in this virtual host
-
bindingsForQueue
What is bound to a queue.The answer AMQP cannot give, and the one that identifies an unroutable message: a publish that nothing receives is a routing key with no binding, and until now the only way to find that out was to publish and be told.
- Parameters:
queue- the queue- Returns:
- its bindings, including the implicit default-exchange one
-
vhosts
- Returns:
- every virtual host on the broker. Not scoped to this client's vhost
-
createVhost
Creates a virtual host, or does nothing when it is already there.- Parameters:
name- what to call it
-
deleteVhost
Deletes a virtual host and everything in it.Every queue, every message in them, every exchange, every binding and every permission, with no confirmation and nothing to undo it. There is no soft delete in this API and this method does not invent one.
- Parameters:
name- the virtual host to remove
-
users
- Returns:
- every user on the broker
-
createUser
Creates or updates a user.The password does not leave this process. It is hashed here, with RabbitMQ's own salted SHA-256, and the broker is sent
password_hashandhashing_algorithm. Up to 0.1.x the password itself was sent and the broker hashed it, which put it in a request body over whatever transport the base URL named — often plain HTTP. HTTPS is still right for this API: the hash is not the password, and is still enough to stand up a broker the password works against.- Parameters:
name- the userpassword- its passwordtags-administrator,monitoring,management,policymaker, or none for a user that can connect and nothing else
-
createUser
Creates or updates a user from a hash computed elsewhere.admin.createUser("orders-service", PasswordHash.of(hashFromVault, PasswordHash.SHA256));- Parameters:
name- the userhash- its password hashtags- as forcreateUser(String, String, String...)
-
deleteUser
- Parameters:
name- the user to remove. Connections it already has are closed by the broker
-
deleteUsers
Deletes several users in one request.A name that is not a user is skipped rather than refused, so this is safe to repeat.
POST /api/users/bulk-delete.- Parameters:
names- the users to remove
-
usersWithoutPermissions
Users that cannot reach any virtual host.The broker's own answer to "which accounts are left over?". A user here can still log in to the management API if it has a tag, so it is not necessarily harmless — but it is not used by any application, because no application can connect as it.
- Returns:
- every user with no permissions in any virtual host
-
permissions
- Returns:
- every permission on the broker, across all virtual hosts
-
grant
Grants a user access to this client's virtual host.Three regular expressions, matched against resource names.
".*"for all three is unrestricted access — what most tutorials show, and rarely what anybody means.- Parameters:
user- the userconfigure- what it may declare and deletewrite- what it may publish toread- what it may consume from
-
revoke
- Parameters:
user- the user losing access to this client's virtual host
-
policies
- Returns:
- the policies in this virtual host
-
putPolicy
Creates or replaces a policy.Unlike a queue argument, this can be changed later — which is the reason to prefer a policy for anything operational. Note that where several policies match, the highest priority wins outright; the definitions are not merged.
- Parameters:
name- what to call itpattern- a regular expression matched against namesdefinition- what to setpriority- higher wins
-
deletePolicy
- Parameters:
name- the policy to remove. What it was applying reverts immediately
-
shovels
- Returns:
- the shovels the broker is running, or an empty list when the shovel plugin is not enabled — which is a configuration fact rather than a failure
-
federationUpstreams
- Returns:
- the upstreams defined in this virtual host, or an empty list when the federation plugin is not enabled
-
putFederationUpstream
Declares an upstream, or replaces one of the same name.This alone federates nothing. An upstream names a broker; a policy whose definition carries
federation-upstreamis what links anything to it. That two-step is the usual reason federation appears not to work, and nothing reports it because nothing is wrong.admin.putFederationUpstream("other-dc", "amqp://user:pass@other-dc:5672", Map.of("expires", 3_600_000)); admin.putPolicy("federate", "^events\\.", Map.of("federation-upstream", "other-dc"), 1);Set
expiresunless there is a reason not to. Without it the queue federation creates on the upstream survives forever with nothing consuming from it, and a decommissioned downstream leaves a queue growing on somebody else's broker.- Parameters:
name- what to call it, and what a policy will refer touri- where the upstream broker is, credentials includedsettings-expires,message-ttl,ack-mode,max-hops,prefetch-count; may be empty
-
deleteFederationUpstream
- Parameters:
name- the upstream to remove. Any link using it stops; a policy still naming it stays and quietly matches nothing
-
federationLinks
The links that actually exist.The only proof federation is working. An upstream can be declared and a policy can match and there can still be no link, because the upstream is unreachable or its credentials are wrong — and none of that surfaces anywhere else.
- Returns:
- the links in this virtual host, or empty when the federation management plugin is not enabled
-
declareShovel
Declares a dynamic shovel, or replaces one of the same name.A shovel consumes. A message it moves is gone from the source, which is what makes it right for draining a queue during a migration and wrong for copying a stream of events — federation does that. Pointing one at a queue somebody is still reading produces two consumers racing, and the shovel usually wins.
admin.declareShovel("drain-orders", Map.of( "src-protocol", "amqp091", "src-uri", "amqp://old-broker", "src-queue", "orders", "dest-protocol", "amqp091", "dest-uri", "amqp://new-broker", "dest-queue", "orders"));- Parameters:
name- what to call itdefinition- the shovel's source and destination
-
deleteShovel
- Parameters:
name- the shovel to remove. It stops moving messages immediately
-
parameters
Runtime parameters of one component.Federation upstreams and dynamic shovels are both stored this way, which is why they are declared and deleted identically and why neither appears in a topology export that only looks at queues and exchanges.
- Parameters:
component-federation-upstream,shovel, or another plugin's- Returns:
- the parameters, or empty when the plugin providing that component is absent
-
health
The broker's own health checks.if (!admin.health().isHealthy()) { admin.health().failures().forEach(f -> log.error("{}", f)); }- Returns:
- a view over
/api/health/checks/
-
exportDefinitions
Exports everything the broker is configured to be.Queues, exchanges, bindings, vhosts, users, permissions, topic permissions, policies and runtime parameters, in one request. This is the backup: assembling one by walking the topology misses federation upstreams and shovels, which are parameters, and the restored broker looks complete while federating nothing.
No messages. This is configuration only.
- Returns:
- the definitions, with the broker's own JSON kept verbatim
-
exportVhostDefinitions
- Returns:
- the definitions for the current virtual host alone, which omits the cluster-wide sections — users, permissions and global parameters are not scoped to a vhost
-
importDefinitions
Applies a definitions document to this broker.This is a merge, not a replacement. Everything in the document is created or updated; nothing absent from it is removed. Importing an old backup therefore restores what was lost without deleting what has been added since — which is usually what is wanted, and is not what "restore" sounds like.
Users in a definitions file carry password hashes rather than passwords, so importing one recreates accounts that accept the original passwords. Treat the file as a credential.
- Parameters:
json- a definitions document, as produced byexportDefinitions()
-
connections
- Returns:
- every client connection to the broker, across all virtual hosts
-
connection
- Parameters:
name- the broker's name for the connection, fromConnectionInfo.name()- Returns:
- it, or empty if it has since closed
-
closeConnection
Closes a client connection.The client sees a connection closed by the broker, with the reason given. A well-built client will reconnect immediately, which makes this a way to force a reconnection — to move a client off a node before maintenance, for instance — rather than a way to keep something disconnected.
- Parameters:
name- fromConnectionInfo.name()reason- told to the client, and worth making specific
-
channels
- Returns:
- every open channel, across all connections
-
consumers
- Returns:
- every consumer in the current virtual host, with the queue each is attached to
-
declareQueue
Declares a queue.Note that AMQP can do this, and usually should: a queue an application depends on is best declared by that application, at startup, so it exists before the first publish. This exists for the cases AMQP cannot serve — provisioning a queue for a team that has not deployed yet, or restoring one from a backup.
- Parameters:
name- the queuedurable- whether it survives a broker restartarguments- queue arguments, or an empty map
-
deleteQueue
- Parameters:
name- the queue to delete, with everything in it
-
purgeQueue
Discards every message in a queue, keeping the queue.Irreversible, and there is no confirmation. It is genuinely the right tool for a dead-letter queue full of messages that have been analysed and cannot be replayed — and it is exactly as fast on a queue holding something important.
- Parameters:
name- the queue to empty
-
declareExchange
public void declareExchange(String name, String type, boolean durable, Map<String, Object> arguments) - Parameters:
name- the exchangetype-direct,topic,fanoutorheadersdurable- whether it survives a broker restartarguments- exchange arguments, or an empty map
-
deleteExchange
- Parameters:
name- the exchange to delete. Its bindings go with it
-
bindQueue
Binds a queue to an exchange.- Parameters:
source- the exchangequeue- the queueroutingKey- the routing key or patternarguments- binding arguments, which is where a headers exchange keeps its rules
-
bindExchange
public void bindExchange(String source, String destination, String routingKey, Map<String, Object> arguments) Binds an exchange to another exchange.- Parameters:
source- the upstream exchangedestination- the downstream exchangeroutingKey- the routing key or patternarguments- binding arguments
-
unbind
Removes a binding.Takes the whole
BindingInforather than a routing key because a binding is identified by its properties key, which arrives already percent-encoded and must not be encoded again.- Parameters:
binding- one returned bybindings()orbindingsForQueue(String)
-
operatorPolicies
Policies an operator sets and a user cannot override.Same shape as
policies()and a different purpose: where both apply, the operator policy wins. These are the guard rails — a maximum queue length across a shared broker, say — that survive a team applying its own policy.- Returns:
- every operator policy in the current virtual host
-
putOperatorPolicy
public void putOperatorPolicy(String name, String pattern, Map<String, Object> definition, int priority) - Parameters:
name- the policy namepattern- a regular expression matched against queue or exchange namesdefinition- the settings to applypriority- higher wins among matching operator policies
-
deleteOperatorPolicy
- Parameters:
name- the operator policy to remove
-
vhostLimits
- Returns:
- the limits set on every virtual host
-
setVhostLimit
- Parameters:
limit-LimitInfo.MAX_CONNECTIONSorLimitInfo.MAX_QUEUESvalue- the ceiling
-
clearVhostLimit
- Parameters:
limit- the limit to remove, restoring "no limit"
-
userLimits
- Returns:
- the limits set on every user
-
setUserLimit
- Parameters:
user- the userlimit-max-connectionsormax-channelsvalue- the ceiling
-
clearUserLimit
- Parameters:
user- the userlimit- the limit to remove
-
topicPermissions
Routing-key authorisation on topic exchanges.Separate from
permissions(), and easy to miss: a user with no topic permissions is unrestricted on topic exchanges. An empty list here means nothing is being enforced, however carefully the ordinary permissions are set.- Returns:
- every topic permission on the broker
-
grantTopic
- Parameters:
user- the userexchange- the topic exchangewrite- a routing-key pattern this user may publish withread- a routing-key pattern this user may bind and consume with
-
revokeTopic
- Parameters:
user- the user whose topic permissions in this virtual host are removed, which restores unrestricted access rather than removing it
-
whoami
- Returns:
- the user these credentials belong to, and its tags. Worth calling at startup: a missing tag reported here is far easier to act on than the 403 it becomes later
-
nodes
- Returns:
- every node in the cluster
-
clusterName
- Returns:
- the cluster's name
-
featureFlags
- Returns:
- every feature flag and its state. A flag whose stability is
requiredand whose state is notenabledwill block the next major upgrade
-
deprecatedFeaturesInUse
- Returns:
- the deprecated features this broker is actually using. The upgrade readiness list: everything on it stops working at some future version, and an empty list is the answer you want before upgrading
-
globalParameters
- Returns:
- the cluster-wide parameters, which are not scoped to a virtual host. These use
GlobalParameterInforather thanParameterInfobecause their values are not objects:internal_cluster_idis a string andcluster_tagsis an array, and every broker has both
-
rebalanceQueues
public void rebalanceQueues()Moves queue leaders so each node leads a fair share.After a rolling restart every quorum queue and stream tends to be led from whichever node came back first, and that node does most of the work. This asks the broker to spread the leaders out again.
POST /api/rebalance/queues.Asynchronous. The call returns once the broker has accepted the request, not when the leaders have moved; the outcome is reported only in the broker's log. Each leader that moves makes its queue briefly unavailable, so this is a maintenance operation rather than something to run on a timer.
-
extensions
- Returns:
- the JavaScript files that management plugins have registered with the UI — the
plugin list as the management API sees it, so
stream.jshere meansrabbitmq_stream_managementis enabled.GET /api/extensions
-
authAttempts
Login attempts one node has counted, per protocol.The only record of a failed login: it never becomes a connection, so nothing else lists it. Counted per node, which is why a node is named —
NodeInfo.name().- Parameters:
node- a node name, such asrabbit@host- Returns:
- the counters, or empty when there is no such node
-
authAttemptsBySource
Login attempts one node has counted, per remote address and username.Empty unless the broker is told to track them. The setting is
track_auth_attempt_sourcein therabbitapplication, off by default, and has norabbitmq.confkey on 3.13 or 4.x: it goes inadvanced.configas[{rabbit, [{track_auth_attempt_source, true}]}]. Off because every distinct address and username becomes an entry, and a scanner trying many usernames would grow the table without limit.- Parameters:
node- a node name- Returns:
- the counters, or empty when source tracking is off or there is no such node
-
resetAuthAttempts
Zeroes one node's login counters, the per-protocol totals and the per-source entries alike — after a misconfigured client is fixed, say, so a failure that follows is a new one.- Parameters:
node- a node name
-
streamConnections
Connections over the stream protocol, across all virtual hosts.These need the
rabbitmq_stream_managementplugin, and without it every stream method here answers an empty list — the same rule asshovels(): a plugin that is not enabled is a fact about the broker, not a failure.extensions()containingstream.jsis how to tell the two kinds of empty apart.The broker reports stream connections, publishers and consumers through its statistics, so one that appeared within the last statistics interval — five seconds by default — is not listed yet.
- Returns:
- every stream protocol connection
-
streamPublishers
- Returns:
- the stream publishers in this virtual host
-
streamPublishers
- Parameters:
stream- a stream in this virtual host- Returns:
- the publishers writing to it
-
streamConsumers
There is no per-stream form of this, unlikestreamPublishers(String):/api/stream/consumers/{vhost}/{stream}answers 400 on 3.13 and 4.x alike. Filter onStreamConsumerInfo.stream()instead.- Returns:
- the stream consumers in this virtual host
-
vhost
- Returns:
- the virtual host this client reads
-
close
public void close()- Specified by:
closein interfaceAutoCloseable
-
toString
-