Skip to content

Instantly share code, notes, and snippets.

@bxgrant
Last active December 25, 2015 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxgrant/5388ab9a1781ac598800 to your computer and use it in GitHub Desktop.
Save bxgrant/5388ab9a1781ac598800 to your computer and use it in GitHub Desktop.
Gearman Java Example
package com.acme;
import org.gearman.client.GearmanJobResult;
import org.gearman.client.GearmanJobResultImpl;
import org.gearman.common.GearmanNIOJobServerConnection;
import org.gearman.worker.AbstractGearmanFunction;
import org.gearman.worker.GearmanFunction;
import org.gearman.worker.GearmanFunctionFactory;
import org.gearman.worker.GearmanWorker;
import org.gearman.worker.GearmanWorkerImpl;
public class GearmanTestRunner
{
private GearmanNIOJobServerConnection _connection;
private GearmanWorker _worker;
private String _host;
private int _port;
public GearmanTestRunner(String host, int port)
{
_host = host;
_port = port;
}
public void execute()
{
_connection = new GearmanNIOJobServerConnection(_host, _port);
_worker = new GearmanWorkerImpl();
_worker.addServer(_connection);
GearmanFunctionFactory f1 = new GearmanFunctionFactory()
{
@Override
public String getFunctionName()
{
return "Test.functionOne";
}
@Override
public GearmanFunction getFunction()
{
return new AbstractGearmanFunction("Test.functionOne")
{
@Override
public GearmanJobResult executeFunction()
{
String response = "{\"success\": true, \"name\": \"Test.functionOne\"}";
return new GearmanJobResultImpl(this.jobHandle, true, response.getBytes(), new byte[0], new byte[0], 0, 0);
}
};
}
};
_worker.registerFunctionFactory(f1);
GearmanFunctionFactory f2 = new GearmanFunctionFactory()
{
@Override
public String getFunctionName()
{
return "Test.functionTwo";
}
@Override
public GearmanFunction getFunction()
{
return new AbstractGearmanFunction("Test.functionTwo")
{
@Override
public GearmanJobResult executeFunction()
{
String response = "{\"success\": true, \"name\": \"Test.functionTwo\"}";
return new GearmanJobResultImpl(this.jobHandle, true, response.getBytes(), new byte[0], new byte[0], 0, 0);
}
};
}
};
_worker.registerFunctionFactory(f2);
_worker.work();
}
private static void printUsage()
{
System.out.println("Usage: <gearman-host> <gearman-port>");
}
public static void main(String[] args)
{
int count = args.length;
if (count != 2)
{
printUsage();
System.exit(0);
}
String host = args[0];
String portStr = args[1];
int port = -1;
try
{
port = Integer.parseInt(portStr);
}
catch(NumberFormatException nfe)
{
System.out.println("gearman-port is not a valid number: " + portStr);
printUsage();
System.exit(0);
}
GearmanTestRunner runner = new GearmanTestRunner(host, port);
runner.execute();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment