Created
August 1, 2015 09:01
-
-
Save nevenc/2e75a09153e0d68365ef to your computer and use it in GitHub Desktop.
REST Client (multi-threaded)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package phonebook.client; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
import javax.ws.rs.client.Client; | |
import javax.ws.rs.client.ClientBuilder; | |
import javax.ws.rs.client.Entity; | |
import javax.ws.rs.client.WebTarget; | |
import javax.ws.rs.core.MediaType; | |
import javax.ws.rs.core.Response; | |
import com.github.javafaker.Faker; | |
import phonebook.model.Entry; | |
public class SaveToPhonebook { | |
private static final int DEFAULT_NUMBER_OF_ENTRIES_TO_SAVE = 100; | |
private static final int DEFAULT_NUMBER_OF_THREADS = 1; | |
private static final String[] PHONE_TYPE = { "Home", "Work", "Fax", "Cell", "Other" }; | |
private static final Faker FAKER = new Faker(); | |
private static final String REST_RESOURCE = "http://localhost:8080/api/entries"; | |
private static final Client client = ClientBuilder.newClient(); | |
public static void main(String[] args) throws InterruptedException { | |
int entryCount = DEFAULT_NUMBER_OF_ENTRIES_TO_SAVE; | |
int workerCount = DEFAULT_NUMBER_OF_THREADS; | |
if ( args.length != 2 ) { | |
System.out.println("Usage: SaveToPhonebook <num_of_entries> <num_of_workers>"); | |
System.out.println(" using default values: SaveToPhonebook 100 1"); | |
} else { | |
entryCount = Integer.parseInt(args[0]); | |
workerCount = Integer.parseInt(args[1]); | |
} | |
WebTarget target = client.target(REST_RESOURCE); | |
ExecutorService threadpool = Executors.newFixedThreadPool(workerCount); | |
Runnable task = () -> { | |
String threadName = Thread.currentThread().getName(); | |
Entry entry = new Entry(null,FAKER.name().fullName(),FAKER.phoneNumber().phoneNumber(),FAKER.options().option(PHONE_TYPE)); | |
Entity<Entry> entity = Entity.entity(entry, MediaType.APPLICATION_JSON); | |
Response response = target.request().accept(MediaType.APPLICATION_JSON_TYPE).post(entity); | |
String status = Integer.toString(response.getStatus()); | |
String location = response.getHeaderString("Location"); | |
String message = String.format("[%s] status: %s, location: %s", threadName, status, location); | |
System.out.println(message); | |
}; | |
for (int i=0; i<entryCount; i++) { | |
threadpool.execute(task); | |
} | |
threadpool.shutdown(); | |
threadpool.awaitTermination(60, TimeUnit.SECONDS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment