Main Components of Java Spring Boot

Main Components of Java Spring Boot

1. Services

In a microservices architecture, a service is a self-contained unit of functionality that performs a specific business task. Each service is developed, deployed, and scaled independently. Services communicate with each other using APIs.

Main Components of Java Spring Boot

Java Example
```java
// User Service
@SpringBootApplication
@RestController
@RequestMapping("/users")
public class UserService {
    public static void main(String[] args) {
        SpringApplication.run(UserService.class, args);
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable String id) {
        // Logic to retrieve user by ID
        return new User(id, "John Doe", "john.doe@example.com");
    }
}

// Product Service
@SpringBootApplication
@RestController
@RequestMapping("/products")
public class ProductService {
    public static void main(String[] args) {
        SpringApplication.run(ProductService.class, args);
    }

    @GetMapping("/{id}")
    public Product getProductById(@PathVariable String id) {
        // Logic to retrieve product by ID
        return new Product(id, "Laptop", 1000.0);
    }
}
```

2. Service Registry

A service registry is a database that contains the locations of all service instances in the system. Microservices register themselves with the service registry and query it to discover other services.

Java Example
```java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
```

Configuration:
```yaml
server:
  port: 8761
eureka:
  client:
    registerWithEureka: false
    fetchRegistry: false
```

3. API Gateway

The API Gateway acts as a single entry point for all client requests. It routes requests to the appropriate microservices and handles cross-cutting concerns like authentication, logging, and load balancing.

Java Example
```java
@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}
```

Configuration:
```yaml
zuul:
  routes:
    users:
      path: /users/
      serviceId: user-service
    products:
      path: /products/
      serviceId: product-service
```

4. Cloud Infrastructure

Cloud infrastructure provides the environment and resources needed to deploy, manage, and scale microservices. Popular cloud platforms include AWS, Azure, and Google Cloud.

Java Example:

Configuration and deployment to a cloud provider are often managed through cloud-specific tools and services, rather than Java code directly. For example, deploying a Spring Boot application to AWS involves using AWS Elastic Beanstalk or similar services.

5. Containerization and Orchestration

Containerization involves packaging microservices into containers (e.g., Docker) to ensure consistency across environments. Orchestration (e.g., Kubernetes) manages the deployment, scaling, and operation of containers.

Java Example
```dockerfile
FROM openjdk:11-jdk
COPY target/myapp.jar myapp.jar
ENTRYPOINT ["java", "-jar", "/myapp.jar"]
```

Kubernetes Deployment Example:
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: myapp:latest
        ports:
        - containerPort: 8080
```

6. Message Broker

A message broker facilitates asynchronous communication between microservices by routing messages between them. Common message brokers include RabbitMQ and Apache Kafka.

Java Example
```java
@SpringBootApplication
@EnableRabbit
public class MessagingApplication {
    public static void main(String[] args) {
        SpringApplication.run(MessagingApplication.class, args);
    }
}

@Component
public class MessageListener {
    @RabbitListener(queues = "queueName")
    public void receiveMessage(String message) {
        // Handle received message
    }
}
```

Configuration:
```yaml
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
```

7. Security

Security in microservices involves implementing authentication and authorization mechanisms to protect services. Common approaches include using OAuth2, JWT, and API gateways for security policies.

Java Example
```java
@SpringBootApplication
public class SecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SecurityApplication.class, args);
    }
}

@RestController
public class AuthController {
    @PostMapping("/authenticate")
    public String authenticate(@RequestBody AuthRequest authRequest) {
        // Authentication logic
        return "JWT_TOKEN";
    }
}
```

Configuration:
```yaml
spring:
  security:
    oauth2:
      client:
        registration:
          oauth2:
            client-id: clientId
            client-secret: clientSecret
```

8. Monitoring

Monitoring involves tracking the performance and health of microservices. Tools like Prometheus, Grafana, and Spring Boot Actuator are commonly used to collect and visualize metrics.

Java Example
```java
@SpringBootApplication
public class MonitoringApplication {
    public static void main(String[] args) {
        SpringApplication.run(MonitoringApplication.class, args);
    }
}
```

Configuration:
```yaml
management:
  endpoints:
    web:
      exposure:
        include: health, metrics
```