使用 spring reactor 异步事件驱动

13-05-30 32647908
              

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<Event<LogEvent>>

/*

* log 事件异步处理者.

*/

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

public void accept(Event<LogEvent> 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<LogEvent> 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 + "]";

}

}

              

1
banq
2013-06-03 08:32

非常好,非常感谢分享。