Skip to content

Instantly share code, notes, and snippets.

@AlexMocioi
Created May 23, 2014 12:21
Show Gist options
  • Save AlexMocioi/3644ca9b3a054052d993 to your computer and use it in GitHub Desktop.
Save AlexMocioi/3644ca9b3a054052d993 to your computer and use it in GitHub Desktop.
Java Gearman Worker
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aduna11java;
import org.gearman.Gearman;
import org.gearman.GearmanFunction;
import org.gearman.GearmanFunctionCallback;
import org.gearman.GearmanServer;
import org.gearman.GearmanWorker;
/**
* The echo worker polls jobs from a job server and execute the echo function.
*
* The echo worker illustrates how to setup a basic worker
*/
public class Aduna11Java implements GearmanFunction {
/** The echo function name */
public static final String ECHO_FUNCTION_NAME = "aduna11";
/** The host address of the job server */
public static final String ECHO_HOST = "***.***.***.***";
/** The port number the job server is listening on */
public static final int ECHO_PORT = 4730;
public static void main(String... args) {
/*
* Create a Gearman instance
*/
Gearman gearman = Gearman.createGearman();
/*
* Create the job server object. This call creates an object represents
* a remote job server.
*
* Parameter 1: the host address of the job server.
* Parameter 2: the port number the job server is listening on.
*
* A job server receives jobs from clients and distributes them to
* registered workers.
*/
GearmanServer server = gearman.createGearmanServer(
Aduna11Java.ECHO_HOST, Aduna11Java.ECHO_PORT);
/*
* Create a gearman worker. The worker poll jobs from the server and
* executes the corresponding GearmanFunction
*/
GearmanWorker worker = gearman.createGearmanWorker();
/*
* Tell the worker how to perform the echo function
*/
worker.addFunction(Aduna11Java.ECHO_FUNCTION_NAME, new Aduna11Java());
/*
* Tell the worker that it may communicate with the this job server
*/
worker.addServer(server);
}
@Override
public byte[] work(String function, byte[] data,
GearmanFunctionCallback callback) throws Exception {
/*
* The work method performs the gearman function. In this case, the echo
* function simply returns the data it received
*/
String numar = new String(data, "UTF-8");
long rezultat = Long.parseLong(numar) + 11;
String raspuns = "{\"lucrator\":\"java\", \"rezultat\":" + String.valueOf(rezultat) + "}";
System.out.printf("Am primit spre lucru numărul %s și dau înapoi %s \n",numar,raspuns);
return raspuns.getBytes();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment