Gearman 的使用

111 阅读2分钟

版权所有:转载请标明出处:

-------------------

一.Gearman 的 Job Server 调度程序的使用

1. 启动Job:   gearman默认端口号为4730。

./gearmand -L 172.16.23.132 -p 4730 -u root -d

-d deamon
-L 监听 IP
-p 端口

2. Gearman 的状态查看(貌似不能用)

telnet localhost 4730

status

 

二.编写worker代码和启动:

1.引入jar

gearman-java-0.6.jar

log4j-1.2.16.jar

slf4j-api-1.6.4.jar

slf4j-simple-1.6.4.jar

 

2.自定义function类:function类就是client端可以根据function.class 来选择执行哪个function

继承 AbstractGearmanFunction类复写executeFunction方法

import org.gearman.client.GearmanJobResult;

import org.gearman.client.GearmanJobResultImpl;

import org.gearman.util.ByteUtils;

import org.gearman.worker.AbstractGearmanFunction;

/**

*function 类

*/

public class UpperCaseFunction extends AbstractGearmanFunction{

    /**

     * 实现业务逻辑的方法

     */

    @Override

    public GearmanJobResult executeFunction() {

        //接收client端传过来的参数

        String param = ByteUtils.fromUTF8Bytes((byte[]) this.data);

 

        //返回结果的字节数组

        byte[] bytes =param.toUpperCase().getBytes();

        //返回结果对象

        GearmanJobResult gjr = new GearmanJobResultImpl(bytes);

        return gjr;

    }

 

}

 

3.worker类:用于启动worker的类。

/**

 *worker  

 */

public class UpperCaseWorker {

    

    @SuppressWarnings("unchecked")

    public static void main(String[] args) {

        List<Class<GearmanFunction>> functions = new ArrayList<Class<GearmanFunction>>();

        String host = "172.16.23.132"; //gearman server address

        int port = 4730;  //server port

        

        //添加function.class到list

        Class<GearmanFunction> func;

        try {

            func = (Class<GearmanFunction>) Class

                    .forName("com.rhf.gearman.worker.UpperCaseFunction");

            if (!GearmanFunction.class.isAssignableFrom(func)) {

                System.out.println(func.getName() + " is not an instance of " + // NOPMD

                        GearmanFunction.class.getCanonicalName());

                return;

            }

            functions.add(func);

        } catch (ClassNotFoundException cfne) {

            System.out.println(cfne.getMessage());

            return;

        }

        //创建worker对象,并启动

        GearmanNIOJobServerConnection conn = new GearmanNIOJobServerConnection(host, port);

        GearmanWorker worker = new GearmanWorkerImpl();

        worker.addServer(conn);

        

        worker.registerFunction(func); //注册function

        worker.work(); //work 开始

    }

}

三. Worker的第二种写法:

import org.gearman.client.GearmanJobResult;

import org.gearman.client.GearmanJobResultImpl;

import org.gearman.common.Constants;

import org.gearman.common.GearmanNIOJobServerConnection;

import org.gearman.worker.AbstractGearmanFunction;

import org.gearman.worker.GearmanWorker;

import org.gearman.worker.GearmanWorkerImpl;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

 

/**

* @author: Laud

* @date: 2013-2-1 下午5:23:03

*/

public class EchoWorker extends AbstractGearmanFunction {

    private final static Logger log = LoggerFactory.getLogger(EchoWorker.class);

 

    public static void main(String[] args) {

        GearmanWorker worker = new GearmanWorkerImpl();

        GearmanNIOJobServerConnection conn = new GearmanNIOJobServerConnection(

                "172.16.23.132", Constants.GEARMAN_DEFAULT_TCP_PORT);

        worker.addServer(conn);

        worker.registerFunction(EchoWorker.class);

        log.debug("启动服务...");

        worker.work();

    }

 

    @Override

    public GearmanJobResult executeFunction() {

        log.debug("调用了worker方法!");

        GearmanJobResult jr = new GearmanJobResultImpl("哈哈".getBytes());

        return jr;

    }

}

 

三.client端的代码:

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.GearmanJobServerConnection;

import org.gearman.common.GearmanNIOJobServerConnection;

import org.gearman.example.ReverseClient;

import org.gearman.util.ByteUtils;

 

import com.rhf.gearman.worker.UpperCaseFunction;

 

public class UpperCaseClient {

    private GearmanClient client;

 

    public UpperCaseClient(GearmanClient client){

        this.client = client;

    }

 

    public String reverse(String input) {

        //获取要调用的function类类全名

        String function = UpperCaseFunction.class.getCanonicalName();

        String uniqueId = null;

        byte[] data = ByteUtils.toUTF8Bytes(input);

        GearmanJobResult res = null;

        GearmanJob job = GearmanJobImpl.createBackgroundJob(function, data, uniqueId);

        //GearmanJobImpl.createBackgroundJob(functionName, data, priority, id)

        String value = "";

        client.submit(job); //提交工作

 

        try {

            //获取funtion执行后的返回值

            res = job.get();

            value = ByteUtils.fromUTF8Bytes(res.getResults());

        } catch (Exception e) {

            e.printStackTrace(); // NOPMD

        }

        return value;

    }

    /**

     *关闭gearmanclient

     */

    public void shutdown() throws IllegalStateException {

        if (client == null) {

            throw new IllegalStateException("No client to shutdown");

        }

        client.shutdown();

    }

 

    public static void main(String[] args) {

        String host = "172.16.23.132";

        int port = 4730;

        GearmanJobServerConnection conn = new GearmanNIOJobServerConnection(host, port);

        GearmanClient client = new GearmanClientImpl();

        client.addJobServer(conn); //添加连接

        UpperCaseClient rc = new UpperCaseClient(client);

 

        System.out.println(rc.reverse("rhf")); // NOPMD

        rc.shutdown();

    }

}

 blog.csdn.net/wendelee/ar…