gearman Java Client



import java.util.concurrent.ExecutionException;

import org.gearman.client.GearmanClient;
import org.gearman.client.GearmanClientImpl;
import org.gearman.client.GearmanJob;
import org.gearman.client.GearmanJobImpl;
import org.gearman.client.GearmanJobResult;
import org.gearman.common.GearmanNIOJobServerConnection;
import org.gearman.util.ByteUtils;

class PrintThread extends Thread{
	  public void run(){
		  ClientTest test=new ClientTest("192.168.101.143", 4730);
               System.out.println(test.reverse("hello"));
     	  }
	}
 public class ClientTest {
	GearmanClient client;
	GearmanNIOJobServerConnection con;
	public ClientTest(String host, int port) {
		con = new GearmanNIOJobServerConnection(host, port);
		client = new GearmanClientImpl();
		client.addJobServer(con);//添加一个任务
	}

	public String reverse(String input) {
		String function = ReverseFunction.class.getCanonicalName();//调用函数
		ReverseFunction rf=new ReverseFunction();
		//String reverseValue=rf.reverseValue(input);
		byte[] data = ByteUtils.toUTF8Bytes(input);
		String value = "";
	
		GearmanJob job = GearmanJobImpl.createJob(function, data, null);
		client.submit(job);
		
		try {
			GearmanJobResult rs = job.get();
			value = ByteUtils.fromUTF8Bytes(rs.getResults());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return value;
		
	}
	public  void shutdown()
	{
		if(null==client){
			System.out.println("no client to shutdown");
		}
		client.shutdown();
	}
  public static void main(String[] args) throws Exception {
	  String host="192.168.101.143";
	  int port =4730;
	  String input="woyo";
    ClientTest clientTest=new ClientTest(host, port);
	  /* for(int i=0;i<10;i++){
	      Thread t = new PrintThread();
	      t.start();
	      Thread.sleep(1000);
	    }*/
	   input=clientTest.reverse(input);
	 //  System.out.println(input);
	  clientTest.shutdown();
}
}

你可能感兴趣的:(java,thread)