运用SseEmitter,Spring Event推送数据(SpringBoot2.0)

2018-03-02 08:31:00来历:作者:人点击

共享

 

1.场景

当咱们做异步恳求处理的时分,客户端向服务端的恳求不是当即回来的,而是在服务端有数据的时分才发送给客户端的。本例演示是服务端数据是别的的事情触发并推送给客户端的。

当运用微信或许付出宝扫码付出的时分,在客户付出成功之后,后台得到微信(付出宝)回调需求告诉咱们的客户端付出现已完结,客户端得到告诉后能够做一些后续的操作。
这涉及到后台需求将付出成功的音讯自动推送给客户端,让客户端记忆后续的操作。

  • 客户端向后台(SseController->push)发送异步恳求,客户端处于监听等候状况;
  • 微信(付出宝)付出成功后回调后台(SseController->payCallback模仿);
  • payCallback办法经过applicationContext.publishEvent向体系内部发送付出完结事情;
  • push办法经过payCompletedListener监听事情并经过SseEmitter发送给客户端。

名词解释:SSEserver send event是一种服务端推送的技能,本例运用SseEmitter来完成。

2.SseController

@RestControllerpublic class SseController { @Autowired ApplicationContext applicationContext; @Autowired PayCompletedListener payCompletedListener; @GetMapping("/push") public SseEmitter push(@RequestParam Long payRecordId){final SseEmitter emitter = new SseEmitter();try {payCompletedListener.addSseEmitters(payRecordId,emitter);}catch (Exception e){emitter.completeWithError(e);}return emitter; } @GetMapping("/pay-callback") public String payCallback(@RequestParam Long payRecordId){applicationContext.publishEvent(new PayCompletedEvent(this,payRecordId));return "请到监听处检查音讯"; }}

3.PayCompletedEvent

@[email protected] class PayCompletedEvent extends ApplicationEvent { private Long payRecordId; public PayCompletedEvent(Object source, Long payRecordId) {super(source);this.payRecordId = payRecordId; }}

4.PayCompletedListener

@Componentpublic class PayCompletedListener { private static Map<Long,SseEmitter> sseEmitters = new Hashtable<>(); public void addSseEmitters(Long payRecordId, SseEmitter sseEmitter) {sseEmitters.put(payRecordId, sseEmitter); } @EventListener public void deployEventHandler(PayCompletedEvent payCompletedEvent) throws IOException {Long payRecordId = payCompletedEvent.getPayRecordId();SseEmitter sseEmitter = sseEmitters.get(payRecordId);sseEmitter.send("付出成功");sseEmitter.complete(); }}

5.演示

  • 先拜访http://localhost:8080/push?payRecordId=123,此刻客户端处于等候状况.

  • 再拜访http://localhost:8080/pay-callback?payRecordId=123,模仿回调告诉客户端付出成功,这是会告诉上一步并推送到客户端.

6.源码地址

http://www.wisely.top/2018/03/01/sse-eventlistener/

相关文章

    无相关信息

微信扫一扫

12bet官方网站微信大众渠道