Created
January 31, 2022 13:11
-
-
Save tejasjadhav/d5a4b4efca8e7400236ce18e86dcb00a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 servershutdowntestjava; | |
import okhttp3.ConnectionPool; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import java.io.IOException; | |
import java.util.Scanner; | |
import java.util.UUID; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.TimeUnit; | |
import java.util.logging.Logger; | |
public class App { | |
private static final Logger LOGGER = Logger.getLogger(App.class.toString()); | |
private static final String SERVER_URL = System.getenv().getOrDefault("SERVER_URL", "http://localhost:8080"); | |
private static final int SLEEP_INTERVAL = Integer.parseInt(System.getenv().getOrDefault("SLEEP_INTERVAL", "500")); | |
private final ExecutorService executorService; | |
private final OkHttpClient httpClient; | |
private boolean isRunning; | |
public App() { | |
isRunning = true; | |
executorService = Executors.newFixedThreadPool(10); | |
var connectionPool = new ConnectionPool(10, 1000, TimeUnit.HOURS); | |
httpClient = new OkHttpClient.Builder() | |
.connectionPool(connectionPool) | |
.connectTimeout(1000, TimeUnit.SECONDS) | |
.writeTimeout(1000, TimeUnit.SECONDS) | |
.readTimeout(10000, TimeUnit.SECONDS) | |
.eventListener(new OkHttpEventListener()) | |
.retryOnConnectionFailure(false) | |
.build(); | |
Runtime.getRuntime().addShutdownHook(new Thread(() -> isRunning = false)); | |
} | |
public void run() throws InterruptedException { | |
while (isRunning) { | |
executorService.submit(() -> makeApiCall()); | |
Thread.sleep(SLEEP_INTERVAL); | |
} | |
executorService.shutdown(); | |
} | |
public void manual() { | |
var scanner = new Scanner(System.in); | |
while (isRunning) { | |
scanner.nextLine(); | |
makeApiCall(); | |
} | |
} | |
public void makeApiCall() { | |
var requestId = UUID.randomUUID().toString(); | |
var request = new Request.Builder() | |
.get() | |
.url(SERVER_URL) | |
.header("request-id",requestId) | |
.build(); | |
LOGGER.info(String.format("[%1$s] Sending request for request ID: %2$s", Thread.currentThread().getId(), requestId)); | |
try (var response = httpClient.newCall(request).execute()) { | |
LOGGER.info(String.format("[%1$s] Received response from server for request ID %2$s: %3$s", Thread.currentThread().getId(), requestId, response.body().string())); | |
} catch (IOException e) { | |
LOGGER.info(String.format("[%1$s] Got exception for request ID %2$s: %3$s", Thread.currentThread().getId(), requestId, e.getMessage())); | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String[] args) throws InterruptedException { | |
var app = new App(); | |
var parameter = args.length > 0 ? args[0] : null; | |
if (parameter != null) { | |
app.manual(); | |
} else { | |
app.run(); | |
} | |
} | |
} |
This file contains hidden or 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 main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"math/rand" | |
"net" | |
"net/http" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
var heathStatus = true | |
func HandleIndex(writer http.ResponseWriter, request *http.Request) { | |
requestId := request.Header.Get("request-id") | |
log.Printf("Handling index request with request-id %v\n", requestId) | |
time.Sleep(time.Second * (time.Duration(1 + rand.Intn(3)))) | |
writer.WriteHeader(http.StatusOK) | |
fmt.Fprintf(writer, "ok") | |
} | |
func HandlePing(writer http.ResponseWriter, request *http.Request) { | |
if heathStatus { | |
writer.WriteHeader(http.StatusOK) | |
fmt.Fprintf(writer, "pong") | |
} else { | |
writer.WriteHeader(http.StatusInternalServerError) | |
fmt.Fprintf(writer, "error") | |
} | |
} | |
func main() { | |
rtr := http.NewServeMux() | |
rtr.Handle("/", http.HandlerFunc(HandleIndex)) | |
rtr.Handle("/ping", http.HandlerFunc(HandlePing)) | |
svr := http.Server{ | |
Addr: ":8080", | |
Handler: rtr, | |
} | |
sigChan := make(chan os.Signal, 1) | |
signal.Notify(sigChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) | |
listener, err := net.Listen("tcp", svr.Addr) | |
if err != nil { | |
log.Fatalf("Error while listening on address %v: %v\n", svr.Addr, err) | |
} | |
go func() { | |
err = svr.Serve(listener) | |
}() | |
sig := <-sigChan | |
heathStatus = false | |
log.Printf("Received signal %v, exiting\n", sig) | |
time.Sleep(time.Second * 3) | |
log.Printf("Shutting down server") | |
err = svr.Shutdown(context.Background()) | |
if err != nil { | |
log.Printf("Error while shutting down server: %v\n", err) | |
} | |
log.Printf("Server shut down") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment