spring-cloud-bus.md 13.3 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9
# Spring Cloud Bus

Table of Contents

* [1. Quick Start](#quick-start)
* [2. Bus Endpoints](#bus-endpoints)
  * [2.1. Bus Refresh Endpoint](#bus-refresh-endpoint)
  * [2.2. Bus Env Endpoint](#bus-env-endpoint)

10 11 12 13 14 15 16 17 18 19 20 21 22
- [Spring Cloud Bus](#spring-cloud-bus)
  - [[1. Quick Start](#quick-start)](#1-quick-start)
  - [[2. Bus Endpoints](#bus-endpoints)](#2-bus-endpoints)
    - [[2.1. Bus Refresh Endpoint](#bus-refresh-endpoint)](#21-bus-refresh-endpoint)
    - [[2.2. Bus Env Endpoint](#bus-env-endpoint)](#22-bus-env-endpoint)
  - [[3. Addressing an Instance](#addressing-an-instance)](#3-addressing-an-instance)
  - [[4. Addressing All Instances of a Service](#addressing-all-instances-of-a-service)](#4-addressing-all-instances-of-a-service)
  - [[5. Service ID Must Be Unique](#service-id-must-be-unique)](#5-service-id-must-be-unique)
  - [[6. Customizing the Message Broker](#customizing-the-message-broker)](#6-customizing-the-message-broker)
  - [[7. Tracing Bus Events](#tracing-bus-events)](#7-tracing-bus-events)
  - [[8. Broadcasting Your Own Events](#broadcasting-your-own-events)](#8-broadcasting-your-own-events)
    - [[8.1. Registering events in custom packages](#registering-events-in-custom-packages)](#81-registering-events-in-custom-packages)
  - [[9. Configuration properties](#configuration-properties)](#9-configuration-properties)
茶陵後's avatar
茶陵後 已提交
23 24

* [9. Configuration properties](#configuration-properties)
M
Mao 已提交
25 26 27 28 29 30 31 32 33 34 35

Spring Cloud Bus links the nodes of a distributed system with a lightweight message
broker. This broker can then be used to broadcast state changes (such as configuration
changes) or other management instructions. A key idea is that the bus is like a
distributed actuator for a Spring Boot application that is scaled out. However, it can
also be used as a communication channel between apps. This project provides starters for
either an AMQP broker or Kafka as the transport.

|   |Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at [github](https://github.com/spring-cloud/spring-cloud-bus).|
|---|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
36
## [](#quick-start)[1. Quick Start](#quick-start)
M
Mao 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

Spring Cloud Bus works by adding Spring Boot autconfiguration if it detects itself on the
classpath. To enable the bus, add `spring-cloud-starter-bus-amqp` or`spring-cloud-starter-bus-kafka` to your dependency management. Spring Cloud takes care of
the rest. Make sure the broker (RabbitMQ or Kafka) is available and configured. When
running on localhost, you need not do anything. If you run remotely, use Spring Cloud
Connectors or Spring Boot conventions to define the broker credentials, as shown in the
following example for Rabbit:

application.yml

```
spring:
  rabbitmq:
    host: mybroker.com
    port: 5672
    username: user
    password: secret
```

The bus currently supports sending messages to all nodes listening or all nodes for a
particular service (as defined by Eureka). The `/bus/*` actuator namespace has some HTTP
endpoints. Currently, two are implemented. The first, `/bus/env`, sends key/value pairs to
update each node’s Spring Environment. The second, `/bus/refresh`, reloads each
application’s configuration, as though they had all been pinged on their `/refresh`endpoint.

|   |The Spring Cloud Bus starters cover Rabbit and Kafka, because those are the two most<br/>common implementations. However, Spring Cloud Stream is quite flexible, and the binder<br/>works with `spring-cloud-bus`.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
65
## [](#bus-endpoints)[2. Bus Endpoints](#bus-endpoints)
M
Mao 已提交
66 67 68

Spring Cloud Bus provides two endpoints, `/actuator/busrefresh` and `/actuator/busenv`that correspond to individual actuator endpoints in Spring Cloud Commons,`/actuator/refresh` and `/actuator/env` respectively.

茶陵後's avatar
茶陵後 已提交
69
### [](#bus-refresh-endpoint)[2.1. Bus Refresh Endpoint](#bus-refresh-endpoint)
M
Mao 已提交
70 71 72 73 74 75 76 77 78 79 80

The `/actuator/busrefresh` endpoint clears the `RefreshScope` cache and rebinds`@ConfigurationProperties`. See the [Refresh Scope](#refresh-scope) documentation for
more information.

To expose the `/actuator/busrefresh` endpoint, you need to add following configuration to your
application:

```
management.endpoints.web.exposure.include=busrefresh
```

茶陵後's avatar
茶陵後 已提交
81
### [](#bus-env-endpoint)[2.2. Bus Env Endpoint](#bus-env-endpoint)
M
Mao 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

The `/actuator/busenv` endpoint updates each instances environment with the specified
key/value pair across multiple instances.

To expose the `/actuator/busenv` endpoint, you need to add following configuration to your
application:

```
management.endpoints.web.exposure.include=busenv
```

The `/actuator/busenv` endpoint accepts `POST` requests with the following shape:

```
{
    "name": "key1",
    "value": "value1"
}
```

茶陵後's avatar
茶陵後 已提交
102
## [](#addressing-an-instance)[3. Addressing an Instance](#addressing-an-instance)
M
Mao 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

Each instance of the application has a service ID, whose value can be set with`spring.cloud.bus.id` and whose value is expected to be a colon-separated list of
identifiers, in order from least specific to most specific. The default value is
constructed from the environment as a combination of the `spring.application.name` and`server.port` (or `spring.application.index`, if set). The default value of the ID is
constructed in the form of `app:index:id`, where:

* `app` is the `vcap.application.name`, if it exists, or `spring.application.name`

* `index` is the `vcap.application.instance_index`, if it exists,`spring.application.index`, `local.server.port`, `server.port`, or `0` (in that order).

* `id` is the `vcap.application.instance_id`, if it exists, or a random value.

The HTTP endpoints accept a “destination” path parameter, such as`/busrefresh/customers:9000`, where `destination` is a service ID. If the ID
is owned by an instance on the bus, it processes the message, and all other instances
ignore it.

茶陵後's avatar
茶陵後 已提交
119
## [](#addressing-all-instances-of-a-service)[4. Addressing All Instances of a Service](#addressing-all-instances-of-a-service)
M
Mao 已提交
120 121 122 123 124 125

The “destination” parameter is used in a Spring `PathMatcher` (with the path separator
as a colon — `:`) to determine if an instance processes the message. Using the example
from earlier, `/busenv/customers:**` targets all instances of the
“customers” service regardless of the rest of the service ID.

茶陵後's avatar
茶陵後 已提交
126
## [](#service-id-must-be-unique)[5. Service ID Must Be Unique](#service-id-must-be-unique)
M
Mao 已提交
127 128 129 130 131 132 133 134

The bus tries twice to eliminate processing an event — once from the original`ApplicationEvent` and once from the queue. To do so, it checks the sending service ID
against the current service ID. If multiple instances of a service have the same ID,
events are not processed. When running on a local machine, each service is on a different
port, and that port is part of the ID. Cloud Foundry supplies an index to differentiate.
To ensure that the ID is unique outside Cloud Foundry, set `spring.application.index` to
something unique for each instance of a service.

茶陵後's avatar
茶陵後 已提交
135
## [](#customizing-the-message-broker)[6. Customizing the Message Broker](#customizing-the-message-broker)
M
Mao 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148

Spring Cloud Bus uses [Spring Cloud Stream](https://cloud.spring.io/spring-cloud-stream) to
broadcast the messages. So, to get messages to flow, you need only include the binder
implementation of your choice in the classpath. There are convenient starters for the bus
with AMQP (RabbitMQ) and Kafka (`spring-cloud-starter-bus-[amqp|kafka]`). Generally
speaking, Spring Cloud Stream relies on Spring Boot autoconfiguration conventions for
configuring middleware. For instance, the AMQP broker address can be changed with`spring.rabbitmq.*` configuration properties. Spring Cloud Bus has a handful of
native configuration properties in `spring.cloud.bus.*` (for example,`spring.cloud.bus.destination` is the name of the topic to use as the external
middleware). Normally, the defaults suffice.

To learn more about how to customize the message broker settings, consult the Spring Cloud
Stream documentation.

茶陵後's avatar
茶陵後 已提交
149
## [](#tracing-bus-events)[7. Tracing Bus Events](#tracing-bus-events)
M
Mao 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195

Bus events (subclasses of `RemoteApplicationEvent`) can be traced by setting`spring.cloud.bus.trace.enabled=true`. If you do so, the Spring Boot `TraceRepository`(if it is present) shows each event sent and all the acks from each service instance. The
following example comes from the `/trace` endpoint:

```
{
  "timestamp": "2015-11-26T10:24:44.411+0000",
  "info": {
    "signal": "spring.cloud.bus.ack",
    "type": "RefreshRemoteApplicationEvent",
    "id": "c4d374b7-58ea-4928-a312-31984def293b",
    "origin": "stores:8081",
    "destination": "*:**"
  }
  },
  {
  "timestamp": "2015-11-26T10:24:41.864+0000",
  "info": {
    "signal": "spring.cloud.bus.sent",
    "type": "RefreshRemoteApplicationEvent",
    "id": "c4d374b7-58ea-4928-a312-31984def293b",
    "origin": "customers:9000",
    "destination": "*:**"
  }
  },
  {
  "timestamp": "2015-11-26T10:24:41.862+0000",
  "info": {
    "signal": "spring.cloud.bus.ack",
    "type": "RefreshRemoteApplicationEvent",
    "id": "c4d374b7-58ea-4928-a312-31984def293b",
    "origin": "customers:9000",
    "destination": "*:**"
  }
}
```

The preceding trace shows that a `RefreshRemoteApplicationEvent` was sent from`customers:9000`, broadcast to all services, and received (acked) by `customers:9000` and`stores:8081`.

To handle the ack signals yourself, you could add an `@EventListener` for the`AckRemoteApplicationEvent` and `SentApplicationEvent` types to your app (and enable
tracing). Alternatively, you could tap into the `TraceRepository` and mine the data from
there.

|   |Any Bus application can trace acks. However, sometimes, it is<br/>useful to do this in a central service that can do more complex<br/>queries on the data or forward it to a specialized tracing service.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
196
## [](#broadcasting-your-own-events)[8. Broadcasting Your Own Events](#broadcasting-your-own-events)
M
Mao 已提交
197 198 199 200 201 202 203 204 205 206 207

The Bus can carry any event of type `RemoteApplicationEvent`. The default transport is
JSON, and the deserializer needs to know which types are going to be used ahead of time.
To register a new type, you must put it in a subpackage of`org.springframework.cloud.bus.event`.

To customise the event name, you can use `@JsonTypeName` on your custom class or rely on
the default strategy, which is to use the simple name of the class.

|   |Both the producer and the consumer need access to the class definition.|
|---|-----------------------------------------------------------------------|

茶陵後's avatar
茶陵後 已提交
208
### [](#registering-events-in-custom-packages)[8.1. Registering events in custom packages](#registering-events-in-custom-packages)
M
Mao 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

If you cannot or do not want to use a subpackage of `org.springframework.cloud.bus.event`for your custom events, you must specify which packages to scan for events of type`RemoteApplicationEvent` by using the `@RemoteApplicationEventScan` annotation. Packages
specified with `@RemoteApplicationEventScan` include subpackages.

For example, consider the following custom event, called `MyEvent`:

```
package com.acme;

public class MyEvent extends RemoteApplicationEvent {
    ...
}
```

You can register that event with the deserializer in the following way:

```
package com.acme;

@Configuration
@RemoteApplicationEventScan
public class BusConfiguration {
    ...
}
```

Without specifying a value, the package of the class where `@RemoteApplicationEventScan`is used is registered. In this example, `com.acme` is registered by using the package of`BusConfiguration`.

You can also explicitly specify the packages to scan by using the `value`, `basePackages`or `basePackageClasses` properties on `@RemoteApplicationEventScan`, as shown in the
following example:

```
package com.acme;

@Configuration
//@RemoteApplicationEventScan({"com.acme", "foo.bar"})
//@RemoteApplicationEventScan(basePackages = {"com.acme", "foo.bar", "fizz.buzz"})
@RemoteApplicationEventScan(basePackageClasses = BusConfiguration.class)
public class BusConfiguration {
    ...
}
```

All of the preceding examples of `@RemoteApplicationEventScan` are equivalent, in that the`com.acme` package is registered by explicitly specifying the packages on`@RemoteApplicationEventScan`.

|   |You can specify multiple base packages to scan.|
|---|-----------------------------------------------|

茶陵後's avatar
茶陵後 已提交
257
## [](#configuration-properties)[9. Configuration properties](#configuration-properties)
M
Mao 已提交
258 259

To see the list of all Bus related configuration properties please check [the Appendix page](appendix.html).
茶陵後's avatar
茶陵後 已提交
260 261

if (window.parent == window) {(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1\*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-2728886-23', 'auto', {'siteSpeedSampleRate': 100});ga('send', 'pageview');}