Microservices_Batch_2022_solved
Microservices_Batch_2022_solved
employee-service
├── src/main/java/com/example/employeeservice
│ ├── EmployeeServiceApplication.java
│ ├── controller
│ │ └── EmployeeController.java
│ ├── model
│ │ └── Employee.java
│ ├── repository
│ │ └── EmployeeRepository.java
│ ├── service
│ └── EmployeeService.java
├── src/main/resources
│ └── application.properties
1.1. EmployeeServiceApplication.java
package com.example.employeeservice;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplicat
ion;
@SpringBootApplication
public class EmployeeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(EmployeeServiceApplication.class,
args);
}
}
package com.example.employeeservice.model;
import jakarta.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
package com.example.employeeservice.repository;
import com.example.employeeservice.model.Employee;
import
org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends
JpaRepository<Employee, Long> {
}
package com.example.employeeservice.service;
import com.example.employeeservice.model.Employee;
import
com.example.employeeservice.repository.EmployeeRepository
;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository repository;
employee.setDepartment(updatedEmployee.getDepartment());
employee.setSalary(updatedEmployee.getSalary());
return repository.save(employee);
}).orElseThrow(() -> new
RuntimeException("Employee not found"));
}
import com.example.employeeservice.model.Employee;
import
com.example.employeeservice.service.EmployeeService;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/employees")
public class EmployeeController {
@Autowired
private EmployeeService service;
@PostMapping
public ResponseEntity<Employee>
createEmployee(@RequestBody Employee employee) {
return
ResponseEntity.ok(service.createEmployee(employee));
}
@GetMapping
public ResponseEntity<List<Employee>>
getAllEmployees() {
return
ResponseEntity.ok(service.getAllEmployees());
}
@GetMapping("/{id}")
public ResponseEntity<Employee>
getEmployeeById(@PathVariable Long id) {
return service.getEmployeeById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PutMapping("/{id}")
public ResponseEntity<Employee>
updateEmployee(@PathVariable Long id, @RequestBody
Employee employee) {
return
ResponseEntity.ok(service.updateEmployee(id, employee));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void>
deleteEmployee(@PathVariable Long id) {
service.deleteEmployee(id);
return ResponseEntity.noContent().build();
}
}
spring.datasource.url=jdbc:mysql://localhost:3306/employe
e_db
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
server.port=8081
package com.example.eureka;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplica
tion;
import
org.springframework.cloud.netflix.eureka.server.EnableEu
rekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,
args);
}
}
package com.example.eureka;
import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Eureka Client!";
}
}
# Eureka Server
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
# Eureka Client
eureka.client.service-
url.defaultZone=http://localhost:8761/eureka/
spring.application.name=eureka-client
package com.example.eureka;
import
org.springframework.web.bind.annotation.GetMapping;
import
org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Eureka Client!";
}
}
# Eureka Server
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
# Eureka Client
eureka.client.service-
url.defaultZone=http://localhost:8761/eureka/
spring.application.name=eureka-client
package com.example.springdatajpa.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Constructors
public User() {}
package com.example.springdatajpa.repository;
import com.example.springdatajpa.entity.User;
import
org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends
JpaRepository<User, Long> {
// Custom query methods (optional)
User findByEmail(String email);
}
import com.example.springdatajpa.entity.User;
import
com.example.springdatajpa.repository.UserRepository;
import
org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
// Get user by ID
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
// Update user
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id,
@RequestBody User userDetails) {
User user =
userRepository.findById(id).orElse(null);
if (user != null) {
user.setName(userDetails.getName());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
return null;
}
// Delete user
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
# Enable H2 console
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Docker Architecture
Docker's architecture consists of the following
components:
1. Docker Client:
o The interface for users to interact with Docker
(e.g., docker CLI commands).
o Sends commands to the Docker Daemon using REST
APIs.
2. Docker Daemon:
o Runs on the host machine.
o Responsible for managing Docker objects like
containers, images, and networks.
o Handles building, running, and distributing
Docker containers.
3. Docker Registry:
o A repository for storing Docker images.
o Public registries like Docker Hub or private
registries can be used.
4. Docker Objects:
o Images: Read-only templates used to create
containers.
o Containers: Instances of Docker images that can
be run, stopped, or modified.
o Volumes: Persistent storage for containers.
5. Host OS:
o The operating system on which the Docker Daemon
runs.
Five Docker Commands
1. Pull an Image:
Downloads an image from a Docker Registry.
docker pull <image-name>
Example:
docker pull nginx
2. Run a Container:
Starts a container based on an image.
docker run -d -p 8080:80 <image-name>
Example:
docker run -d -p 8080:80 nginx
3. List Running Containers:
Shows all running containers.
docker ps
4. Stop a Container:
Stops a running container.
docker stop <container-id>
5. Build an Image:
Creates a new image from a Dockerfile.
docker build -t <image-name> .
Example:
docker build -t my-app .
Explain Microservices Deployment Patterns with Diagram. 10
Ans:
2. Multiple Service instances per Host Pattern
• Description: Multiple microservices share a single
host.
• Advantages:
o Better resource utilization.
o Reduced infrastructure costs.
• Disadvantages:
o Risk of resource contention.
o Service failures may impact co-located services.