49. 广播你自己的事件

总线可以承载任何类型的 RemoteApplicationEvent。默认的传输是 JSON,反序列化程序需要知道哪些类型将提前使用。要注册新类型,必须将其放入 org.springframework.cloud.bus.event 的子包中。

要自定义事件名称,可以在自定义类上使用 @JsonTypeName,也可以依赖默认策略,即使用类的简单名称。

[Note] Note

生产者和消费者都需要访问类定义。

49.1 在自定义包中注册事件

如果不能或不想为自定义事件使用 org.springframework.cloud.bus.event 子包,则必须使用 @RemoteApplicationEventScan 注解指定要扫描哪些包以查找类型为 RemoteApplicationEvent 的事件。使用 @RemoteApplicationEventScan 指定的包包括子包。

例如,考虑以下称为 MyEvent 的自定义事件:

package com.acme;

public class MyEvent extends RemoteApplicationEvent {
    ...
}

你可以通过以下方式向反序列化程序注册该事件:

package com.acme;

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

如果不指定值,则注册使用 @RemoteApplicationEventScan 的类的包。在这个例子中,com.acme 是通过使用 BusConfiguration 包注册的。

你还可以使用 @RemoteApplicationEventScan 上的 value、basePackages 或 basePackageClasses 属性显式指定要扫描的包,如下例所示:

package com.acme;

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

@RemoteApplicationEventScan 前面的所有示例都是等效的,因为通过在 @RemoteApplicationEventScan 上显式指定包来注册 com.acme 包。

[Note] Note

可以指定要扫描的多个基本包。