|
| 1 | +package com.amazonaws.services.sqs; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.concurrent.ExecutionException; |
| 6 | +import java.util.concurrent.ThreadLocalRandom; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | +import java.util.concurrent.TimeoutException; |
| 9 | + |
| 10 | +import com.amazonaws.regions.Regions; |
| 11 | +import com.amazonaws.services.sqs.model.SendMessageRequest; |
| 12 | + |
| 13 | +public class WidgetStore { |
| 14 | + |
| 15 | + private static boolean running = true; |
| 16 | + private static AmazonSQSRequester sqsRequester; |
| 17 | + private static String requestQueueUrl; |
| 18 | + |
| 19 | + public static void main(String[] args) throws Exception { |
| 20 | + requestQueueUrl = args[0]; |
| 21 | + System.out.println("Starting up store using queue: " + requestQueueUrl); |
| 22 | + |
| 23 | + AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); |
| 24 | + sqsRequester = AmazonSQSRequesterClientBuilder.standard() |
| 25 | + .withAmazonSQS(sqs) |
| 26 | + .build(); |
| 27 | + |
| 28 | + shutdownHooks(sqs); |
| 29 | + |
| 30 | + while (running) { |
| 31 | + Thread.sleep(ThreadLocalRandom.current().nextInt(3000) + 3000); |
| 32 | + |
| 33 | + try { |
| 34 | + requestResponseLoop(); |
| 35 | + } catch (Exception e) { |
| 36 | + e.printStackTrace(); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static void requestResponseLoop() throws InterruptedException, ExecutionException { |
| 42 | + String requestBody = "Dude, we need more widgets!"; |
| 43 | + System.out.println("Sending request: " + requestBody); |
| 44 | + SendMessageRequest request = new SendMessageRequest() |
| 45 | + .withQueueUrl(requestQueueUrl) |
| 46 | + .withMessageBody(requestBody); |
| 47 | + |
| 48 | + try { |
| 49 | + String responseBody = sqsRequester.sendMessageAndGetResponse( |
| 50 | + request, 5, TimeUnit.SECONDS).getBody(); |
| 51 | + System.out.println("Received response: " + responseBody); |
| 52 | + } catch (TimeoutException e) { |
| 53 | + System.out.println("Got tired of waiting for response :("); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + private static void shutdownHooks(AmazonSQS sqs) { |
| 58 | + Runtime.getRuntime().addShutdownHook(new Thread(() -> { |
| 59 | + System.out.println("Shutting down!"); |
| 60 | + sqs.shutdown(); |
| 61 | + })); |
| 62 | + |
| 63 | + Thread shutterDowner = new Thread((Runnable)(() -> { |
| 64 | + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); |
| 65 | + try { |
| 66 | + while (!reader.readLine().equals("exit")); |
| 67 | + } catch (Exception e) { |
| 68 | + } |
| 69 | + running = false; |
| 70 | + System.exit(0); |
| 71 | + }), "WidgetStoreShutterDowner"); |
| 72 | + shutterDowner.start(); |
| 73 | + } |
| 74 | +} |
0 commit comments