jee6 学习笔记 6.3 - @Asynchronous

the idea is to the EJB3.1 @Asynchronous ejbs

screen shot 1: call async ejb without receiving a result

jee6 学习笔记 6.3 - @Asynchronous_第1张图片


screen shot 2: call async ejb and get a result

jee6 学习笔记 6.3 - @Asynchronous_第2张图片

the jsf page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui">
    
<h:head>
    <title>Test EJB3.1 @Asynchronous</title>
</h:head>

<h:body>
	<h:form>
	    <p:panel header="Test EJB3.1 @Asynchronous" toggleable="true" style="width:60%">
	     <h:outputText id="out" value="#{at.message}" escape="false"/>
	     <p:separator/>
	     <p:commandButton value="TestCallAndForget" action="#{at.test1}" update="out"/>
	     <p:spacer width="7"/>
	     <p:commandButton value="TestCallAndGetResult" action="#{at.test2}" update="out"/>
	    </p:panel>
    </h:form>
</h:body>
</html>


the backing bean
package test.jxee.action;

import java.io.Serializable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;

import org.apache.log4j.Logger;

import test.jxee.ejb.AsyncEJB;
import test.jxee.model.TstResult;

@ManagedBean(name="at")
public class AsyncEJBTestBean implements Serializable {

  private static final Logger log = Logger.getLogger(AsyncEJBTestBean.class);
  private String message = "hi there!";
  private @EJB AsyncEJB aejb;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }
  
  // testCallAndForget 
  public String test1() {
    log.debug("testCallAndForget... " + System.currentTimeMillis());
    this.aejb.callAndForget();
    this.setMessage("-- testCallAndForget finished --");
    log.debug("testCallAndForget...done " + + System.currentTimeMillis());
    return null;
  }
  
  // testCallAndGetResult
  public String test2() {
    log.debug("testCallAndGetResult... " + System.currentTimeMillis());
    
    Future<TstResult> callReslt = this.aejb.callAndGetResult();
    
    // blocked? you might do some other task here...
    while(!callReslt.isDone()) {
      try {
        log.debug("AsyncEJB not finished yet, pause 1 second...");
        Thread.sleep(1000);
      }
      catch(InterruptedException  ie) {
        ie.printStackTrace();
      }
    }
    
    try {
      // get computation result, wait for 1 second if necessary
      TstResult myReslt = callReslt.get(1, TimeUnit.SECONDS);
      StringBuffer msg = new StringBuffer();
      msg.append("-- Result Status: ").append(myReslt.getStatus())
          .append(" : ").append(myReslt.getTimeStampFormatted())
          .append(" --");
      this.setMessage(msg.toString());
    }
    catch(ExecutionException ee) {
      this.setMessage("AsyncEJB has execution error: " + ee.getMessage());
    }
    catch(TimeoutException toe) {
      this.setMessage("AsyncEJB timed out: " + toe.getMessage());
    }
    catch(Exception e) {
      this.setMessage("AsyncEJB has error: " + e.getMessage());
    }
    
    log.debug("testCallAndGetResult...done " + System.currentTimeMillis());
    return null;
  }
}


the async ejb:
package test.jxee.ejb;

import java.util.Date;
import java.util.concurrent.Future;

import javax.annotation.PostConstruct;
import javax.ejb.AsyncResult;
import javax.ejb.Asynchronous;
import javax.ejb.Stateless;

import org.apache.log4j.Logger;

import test.jxee.model.TstResult;

/**
 * test @Asynchronous EJBs 
 */
@Stateless
public class AsyncEJB {

  private static final Logger log = Logger.getLogger(AsyncEJB.class);
  
  @PostConstruct
  public void init() {
    log.debug(">>> AsyncEJB inited: " + this);
  }
  
  @Asynchronous
  public void callAndForget() {
    log.debug(">>> callAndForget() started: " + System.currentTimeMillis());
    try {
      Thread.sleep(3000); // simulate long running tasks
    }
    catch(InterruptedException e) {
      e.printStackTrace();
    }
    log.debug(">>> callAndForget() completed: " + System.currentTimeMillis());
  }
  
  @Asynchronous // returns a result
  public Future<TstResult> callAndGetResult() {
    log.debug(">>> callAndGetResult() started: " + System.currentTimeMillis());
    try {
      Thread.sleep(5000); // simulate long running tasks
    }
    catch(InterruptedException e) {
      e.printStackTrace();
    }
    // send back result
    TstResult reslt = new TstResult(new Date(), TstResult.STAT.OK);
    log.debug(">>> callAndGetResult() about to send result: " + System.currentTimeMillis());
    return new AsyncResult<TstResult>(reslt);
  }
}


result vo:
package test.jxee.model;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TstResult implements Serializable {

  public static enum STAT {OK, ERROR, UNKNOWN};
  
  private Date timeStamp;
  private String status;
  
  public TstResult() {}
  
  public TstResult(Date date, STAT stat) {
    this.setTimeStamp(date);
    this.setStatus(stat.toString());
  }
  
  public String getTimeStampFormatted() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return format.format(this.timeStamp);
  }
  public Date getTimeStamp() {
    return this.timeStamp;
  }
  public void setTimeStamp(Date timeStamp) {
    this.timeStamp = timeStamp;
  }
  public String getStatus() {
    return status;
  }
  public void setStatus(String status) {
    this.status = status;
  }
}


uploaded the zipped project so far: ProJee6-phase2.zip

你可能感兴趣的:(EJB3.1,@Asynchronous,AsyncResult)