Server and Monitoring

Loading concept...

πŸš€ Spring Boot: Server and Monitoring

The Story of the Smart Restaurant Kitchen

Imagine you’re running a restaurant. You need:

  • A kitchen that’s already set up and ready to cook (Embedded Server)
  • Security locks on your ingredient storage (SSL/TLS)
  • Magic tools that fix themselves while you cook (DevTools)
  • Prep cooks who start working before customers arrive (Startup Runners)
  • A health inspector who watches everything in real-time (Actuator)

Spring Boot gives you ALL of these, ready to go!


🍳 Embedded Server Configuration

What Is It?

Think of an embedded server like a kitchen that comes built into your restaurant. You don’t need to build the kitchen separatelyβ€”it’s already there when you open the doors!

Traditional Way: Build your app β†’ Put it in a server (like Tomcat) β†’ Hope it works Spring Boot Way: Your app comes WITH its own server inside! Just run it!

The Three Kitchen Types

graph TD A[Spring Boot App] --> B{Choose Your Kitchen} B --> C[πŸ… Tomcat<br/>Default Choice] B --> D[⚑ Jetty<br/>Lightweight] B --> E[🌊 Undertow<br/>High Performance]

Simple Configuration

Change the port (which door customers enter):

# application.properties
server.port=8081

Change to Jetty instead of Tomcat:

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

Common Server Settings:

# How many customers can wait at the door
server.tomcat.max-connections=200

# How many chefs (threads) work at once
server.tomcat.threads.max=100

# Connection timeout (how long to wait)
server.connection-timeout=20000

πŸ’‘ Remember This!

Your app is a self-contained lunch box. Everything it needs is packed inside!


πŸ”’ SSL and TLS Configuration

What Is It?

SSL/TLS is like putting your secret recipe in an unbreakable safe. When someone orders food (sends data), they get a special key. Only they can open their delivery!

Without SSL: Anyone can read your messages With SSL: Messages are scrambled and only the right person can unscramble them

The Secret Handshake

graph TD A[πŸ§‘ Customer Browser] -->|Hello! I want to talk securely| B[πŸͺ Your Server] B -->|Here's my certificate proving I'm real| A A -->|Great! Let's create a secret code| B B -->|Secret code accepted!| C[πŸ” Encrypted Chat Begins]

Setting Up SSL

Step 1: Create a keystore (your safe):

keytool -genkeypair -alias myapp \
  -keyalg RSA -keysize 2048 \
  -storetype PKCS12 \
  -keystore keystore.p12 \
  -validity 365

Step 2: Configure Spring Boot:

# Enable HTTPS
server.ssl.enabled=true

# Where is your safe?
server.ssl.key-store=classpath:keystore.p12

# Password to open the safe
server.ssl.key-store-password=mysecret

# Type of safe
server.ssl.key-store-type=PKCS12

# Name of the key inside
server.ssl.key-alias=myapp

Step 3: Force HTTPS everywhere:

@Configuration
public class HttpsConfig {
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat =
            new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(
            httpToHttpsRedirectConnector());
        return tomcat;
    }
}

πŸ’‘ Key Point!

HTTPS = HTTP + S (Secure). The β€˜S’ means your data travels in an armored truck, not an open bicycle!


πŸ”§ DevTools

What Is It?

DevTools is like having a magic assistant who instantly rebuilds your project whenever you make changes. No more stop-restart-wait-repeat!

The Magic Powers

graph TD A[✏️ You Edit Code] --> B[πŸ”„ DevTools Detects Change] B --> C[⚑ Auto Restart in 1-2 seconds] C --> D[πŸŽ‰ See Changes Instantly!]

How to Get the Magic

Add DevTools:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>

What DevTools Does:

Feature What It Means
Auto Restart App restarts when code changes
LiveReload Browser refreshes automatically
Caching Off Always see fresh templates
Remote Debug Debug apps running elsewhere

Fine-tune the magic:

# Restart when these files change
spring.devtools.restart.additional-paths=src/main/java

# Don't restart for these
spring.devtools.restart.exclude=static/**

# Enable LiveReload (browser auto-refresh)
spring.devtools.livereload.enabled=true

🎯 Pro Tip!

DevTools only works in development. In production, it’s automatically disabled. Your deployed app stays fast and secure!


πŸƒ Startup Runners

What Is It?

Startup Runners are like prep cooks who arrive early and get everything ready before the restaurant opens. Need to load some data? Warm up the cache? Check the database? Runners do it!

Two Types of Runners

graph TD A[App Starting...] --> B{Runner Type?} B --> C[CommandLineRunner<br/>Gets raw arguments] B --> D[ApplicationRunner<br/>Gets parsed arguments] C --> E[βœ… App Ready!] D --> E

CommandLineRunner Example

@Component
public class DataLoader implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("Loading initial data...");
        // Load users, products, settings
    }
}

ApplicationRunner Example

@Component
public class StartupChecker implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        if (args.containsOption("init")) {
            System.out.println("Running initialization...");
        }
    }
}

Control the Order

Have multiple runners? Control who goes first!

@Component
@Order(1)  // This runs first
public class DatabaseInitRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("1. Setting up database...");
    }
}

@Component
@Order(2)  // This runs second
public class CacheWarmupRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("2. Warming up cache...");
    }
}

πŸ’‘ When to Use?

Use runners for one-time startup tasks: loading data, checking connections, sending startup notifications, or warming caches!


πŸ“Š Actuator

What Is It?

Actuator is your app’s health inspector and dashboard. It tells you:

  • Is the app healthy?
  • How much memory is it using?
  • What beans are loaded?
  • Are databases connected?

The Inspection Toolkit

graph TD A[πŸ” Actuator] --> B[/health<br/>Is app alive?] A --> C[/info<br/>App details] A --> D[/metrics<br/>Numbers & stats] A --> E[/env<br/>Environment] A --> F[/beans<br/>All Spring beans]

Setting Up Actuator

Add the dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Configure what to expose:

# Show all endpoints
management.endpoints.web.exposure.include=*

# Or pick specific ones
management.endpoints.web.exposure.include=health,info,metrics

# Change the base path (default is /actuator)
management.endpoints.web.base-path=/manage

# Show full health details
management.endpoint.health.show-details=always

Key Endpoints

Endpoint What It Shows
/actuator/health UP or DOWN status
/actuator/info App version, description
/actuator/metrics CPU, memory, requests
/actuator/env All configuration properties
/actuator/beans Every Spring bean
/actuator/loggers Logging levels
/actuator/httptrace Recent HTTP requests

Custom Health Indicator

@Component
public class PaymentServiceHealth
    implements HealthIndicator {

    @Override
    public Health health() {
        if (isPaymentServiceUp()) {
            return Health.up()
                .withDetail("Payment", "Available")
                .build();
        }
        return Health.down()
            .withDetail("Payment", "Unavailable")
            .build();
    }
}

Security Warning! ⚠️

# In production, NEVER expose everything!
# Only expose what you need
management.endpoints.web.exposure.include=health,info

# Use a different port for management
management.server.port=9090

# Require authentication (via Spring Security)

🎯 Quick Summary

Component What It Does Kitchen Analogy
Embedded Server Runs your app Built-in kitchen
SSL/TLS Encrypts data Security locks
DevTools Fast development Self-cleaning tools
Startup Runners Pre-launch tasks Prep cooks
Actuator Monitoring Health inspector

πŸš€ Your Next Steps

  1. βœ… Run your first app with an embedded server
  2. βœ… Add DevTools for faster development
  3. βœ… Create a startup runner to load sample data
  4. βœ… Explore Actuator endpoints
  5. βœ… Secure with SSL when going to production

You’ve got this! Spring Boot makes the hard stuff easy. Your β€œrestaurant” is ready to serve customers! πŸŽ‰

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.