事件监听机制(四)Spring Cloud Bus自定义实现RemoteApplicationEvent

事件监听机制(四)Spring Cloud Bus自定义实现RemoteApplicationEvent

事件监听实现流程

  1. 事件对象:
    继承自java.util.EventObject对象,由开发者自行定义实现。

  2. 事件源:
    就是触发事件的源头,不同的事件源会触发不同的事件类型。

  3. 事件监听器:
    事件监听器负责监听事件源发出的事件,事件监听器可以通过实现java.util.EventListener这个标识接口.,实现事件监听。

流程总结

事件源可以注册事件监听器对象,并可以向事件监听器对象发送事件对象,事件发生后,事件源将事件对象发给已经注册的所有事件监听器,监听器对象随后会根据事件对象内的相应方法响应这个事件。

相关依赖

 <!-- 整合 Spring Cloud Bus : AMQP -->
	<dependency>
 		 <groupId>org.springframework.cloud</groupId>
 	 	<artifactId>spring-cloud-starter-bus-amqp</artifactId>
	</dependency>

自定义实现

添加自定义事件源pojo

/**
 * @ClassName: User 
 * @Description: 自定义事件源pojo
 * @Author: 尚先生
 * @CreateDate: 2019/3/1 10:08
 * @Version: 1.0
 */
public class User implements Serializable {

    private static final long serialVersionUID = -6789036732613612349L;

    /**
     * ID
     */
    private Long id;

    /**
     * 用户名
     */
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

添加自定义事件

/**
 * @ClassName: UserRemoteApplicationEvent 
 * @Description: 自定义事件
 * @Author: 尚先生
 * @CreateDate: 2019/3/1 10:10
 * @Version: 1.0
 */
public class UserRemoteApplicationEvent extends RemoteApplicationEvent {

    private UserRemoteApplicationEvent() {
    }

	//自定义User 
    public UserRemoteApplicationEvent(User user, String originService,
                                      String destinationService) {
        super(user, originService, destinationService);
    }

}

自定义@Configuration,添加 @RemoteApplicationEventScan

/**
 * @ClassName: BusConfiguration 
 * @Description: 自定义配置扫描类
 * @Author: 尚先生
 * @CreateDate: 2019/3/1 10:15
 * @Version: 1.0
 */
@Configuration
@RemoteApplicationEventScan(basePackageClasses = UserRemoteApplicationEvent.class)
public class BusConfiguration {
}

发布事件

/**
 * @ClassName: BusEventController 
 * @Description: 自定义发布事件
 * @Author: 尚先生
 * @CreateDate: 2019/3/1 10:23
 * @Version: 1.0
 */
@RestController
public class BusEventController implements ApplicationContextAware, ApplicationEventPublisherAware {

	// 时间发布器
    private ApplicationEventPublisher eventPublisher;

	//Spring上下文
    private ApplicationContext applicationContext;


	// 发布事件
    @PostMapping("/bus/event/publish/user")
    public boolean publishUserEvent(@RequestBody User user,
                                    @RequestParam(value = "destination", required = false) String destination) {

        String serviceInstanceId = applicationContext.getId();
        UserRemoteApplicationEvent event = new UserRemoteApplicationEvent(user, serviceInstanceId, destination);
        try {
       		 eventPublisher.publishEvent(event);
       	 	return true;   
       		 } catch (Exception e) {
        	return false;   
          	   }  
   		 }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.eventPublisher = applicationEventPublisher;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

自定义监听实现

 @EventListener
    public void onUserRemoteApplicationEvent(UserRemoteApplicationEvent event) {

        System.out.printf("UserRemoteApplicationEvent - " +
                        " Source : %s , originService : %s , destinationService : %s \n",
                event.getSource(),
                event.getOriginService(),
                event.getDestinationService());
    }

测试代码实现结果

http://localhost:8080/bus/event/publish/user?destination=user-service-client:8081
{
	"id":1,
	"name":"sxs"
}

测试结果

true

后续可扩展

  1. 消息传递
    在下游对应监听中获取消息,进行后续相关处理
  2. 消息存储
    如果消息是在内存或者是缓存中存储,后续可新增查询接口,进行消息存储结果查询

往期文章

博客地址:https://blog.csdn.net/shang_xs
微信公众号地址:http://mp.weixin.qq.com/mp/homepage?__biz=MzUxMzk4MDc1OQ==&hid=2&sn=c6c58c06f6f8403af27b6743648b3055&scene=18#wechat_redirect

完整代码及详情

具体依赖及相关源码参照

https://github.com/dwyanewede/segmentfault-lessons/tree/master/spring-cloud

相关文章推荐

事件监听机制(一)Java事件监听
https://blog.csdn.net/shang_xs/article/details/87911756
事件监听机制(二)Spring事件监听
https://blog.csdn.net/shang_xs/article/details/88048545
事件监听机制(三)Spring Cloud Bus流程分析
https://blog.csdn.net/shang_xs/article/details/88050196
事件监听机制(四)Spring Cloud Bus自定义实现RemoteApplicationEvent
https://blog.csdn.net/shang_xs/article/details/88051207

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Spring Cloud Bus是一个用于在分布式系统中传播状态变化的消息总线。它基于Spring Cloud Stream和Spring Cloud Config构建,可以将消息广播到整个系统中的所有服务实例。通过使用Spring Cloud Bus,可以实现配置的动态刷新、事件的传播和集群中的状态同步。 下面是使用Spring Cloud Bus自定义消息总线的步骤: 1. 添加依赖:在项目的pom.xml文件中添加Spring Cloud Bus的依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> ``` 2. 配置消息代理:在应用的配置文件中配置消息代理,例如使用RabbitMQ作为消息代理: ```yaml spring: rabbitmq: host: localhost port: 5672 username: guest password: guest ``` 3. 发送自定义消息:在需要发送自定义消息的地方,使用Spring Cloud Bus提供的API发送消息。例如,可以使用`/actuator/bus-refresh`端点发送刷新配置的消息: ```shell curl -X POST http://localhost:8080/actuator/bus-refresh ``` 4. 接收自定义消息:在需要接收自定义消息的地方,使用Spring Cloud Bus提供的注解和监听器来接收消息。例如,可以使用`@RefreshScope`注解来刷新配置: ```java @RefreshScope @RestController public class ConfigController { // ... } ``` 通过以上步骤,您可以使用Spring Cloud Bus自定义消息总线来实现配置的动态刷新、事件的传播和集群中的状态同步。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值