java spring reactor_使用 spring reactor 异步事件驱动

本文介绍了如何在Spring MVC中使用Spring Reactor进行异步事件驱动编程。首先通过声明Reactor Bean,然后在Controller中发送事件,最后展示了一个Consumer如何接收并处理这些事件,实现了非阻塞的事件处理。
摘要由CSDN通过智能技术生成

spring reactor 事件异步驱动. 使用了spring的mvc 使用了spring的 @Configuration annotation配置没有写xml文件.

步骤

1:声明 Reactor bean

@Bean(name="reactor")

public Reactor getReactor(){

return new Reactor();

}

2:Controller

@Controller

public class HomeController {

@Autowired

Reactor reactor;

@RequestMapping(value = "/")

public ModelAndView test(HttpServletResponse response) throws IOException {

// lets send some stuff

LogEvent logEvent = new LogEvent();

logEvent.setMessage("hello world");

logEvent.setTimestamp(new Date());

logEvent.setSource("test");

logEvent.setO(reactor);

// send

reactor.notify("log.event", Fn.event(logEvent));

System.out.println("after notified");

Map model=new HashMap();

model.put("result", "您的事件已受理.稍后将会通知你.");

model.put("success", true);

return new ModelAndView("home",model);

}

}

第三步 :Consumer 这里Consumer 可以是任意类型

package springarach.archtype.consumer;

import reactor.fn.Event;

import reactor.spring.context.annotation.On;

import springarach.archtype.event.LogEvent;

import com.alibaba.fastjson.JSON;

public class SimpleConsumer { //implements Consumer>

/*

* log 事件异步处理者.

*/

@On(reactor = "@reactor", selector = "log.event")

public void accept(Event event){

System.out.println(Thread.currentThread().getId() + " " + event.getData());

System.out.println(JSON.toJSONString(event.getData().getO()));

}

@On(reactor = "@reactor", selector = "log.event")

public String other(Event event){

try {

Thread.sleep(2000);

} catch (Exception e) {

e.printStackTrace();

}

System.out.println("延迟2秒处理.");

System.out.println(JSON.toJSONString(event.getData().getO()));

return "fdsfd";

}

}

其中logEvent 是

package springarach.archtype.event;

import java.io.Serializable;

import java.util.Date;

public class LogEvent implements Serializable {

private static final long serialVersionUID = 1L;

private String source;

private Date timestamp;

private String message;

Object o;

public Object getO() {

return o;

}

public void setO(Object o) {

this.o = o;

}

public String getSource() {

return source;

}

public void setSource(String source) {

this.source = source;

}

public Date getTimestamp() {

return timestamp;

}

public void setTimestamp(Date timestamp) {

this.timestamp = timestamp;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

@Override

public String toString() {

return "LogEvent [source=" + source + ", timestamp=" + timestamp

+ ", message=" + message + "]";

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值