Skip to content

Latest commit

 

History

History
308 lines (254 loc) · 9.61 KB

File metadata and controls

308 lines (254 loc) · 9.61 KB

Lab 2: Introduction to Microservices and Project Setup

Objective

Set up a Spring Boot microservices project in VS Code. Create individual projects for the UserService, ProductService, and OrderService as part of a microservices architecture.


Steps

1. Open VS Code and Create a New Workspace

  • Open VS Code and create a new folder for your project. Name it MicroservicesProject.
  • This folder will serve as the workspace for the entire microservices project.

2. Set Up Project Structure

  • Inside the MicroservicesProject folder, create three subdirectories:
    • UserService
    • ProductService
    • OrderService

3. Generate UserService with Spring Initializr

  • Open the Command Palette (View > Command Palette or Ctrl+Shift+P).
  • Select Spring Initializr: Generate a Maven Project.
  • Configure the options as follows:
    • Group Id: com.microservices
    • Artifact Id: user-service
    • Name: UserService
    • Add dependencies: Spring Web, MySQL Driver, Spring Data JPA, MySQL Driver.
  • Save the project in the UserService folder.

3.1 Verify Dependencies in pom.xml

   <dependencies>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-data-jpa</artifactId>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-web</artifactId>
           </dependency>

           <dependency>
               <groupId>com.mysql</groupId>
               <artifactId>mysql-connector-j</artifactId>
               <scope>runtime</scope>
           </dependency>
           <dependency>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-test</artifactId>
               <scope>test</scope>
           </dependency>
           <dependency>
               <groupId>jakarta.persistence</groupId>
               <artifactId>jakarta.persistence-api</artifactId>
               <version>3.1.0</version>
           </dependency>
       </dependencies>

4. Configure Application Properties for UserService

  • In the UserService/src/main/resources folder, open application.properties.
  • Add the following configuration to set the application port and database connection:
    server.port=8081
    spring.datasource.url=jdbc:mysql://localhost:3306/user_db
    spring.datasource.username=root
    spring.datasource.password=Test1234!
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true

5. Create the User Entity

  • In the com.microservices.user_service package, create a folder model and a new class called User.java.
  • Define the User entity with fields and annotations:
    package com.microservices.user_service.model;
    
    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;
    
        // Getters and Setters
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    }

6. Create the User Repository

  • In the same package, create a folder repository and a new interface UserRepository.java:
    package com.microservices.user_service.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import com.microservices.user_service.model.User;
    
    public interface UserRepository extends JpaRepository<User, Long> {
    }

7. Implement the User Service Layer

  • Create a folder service and a class UserService.java:

    package com.microservices.user_service.service;
    
    import com.microservices.user_service.model.User;
    import com.microservices.user_service.repository.UserRepository;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class UserService {
        private final UserRepository userRepository;
    
      public UserService(UserRepository userRepository) {
          this.userRepository = userRepository;
      }
    
      public List<User> getAllUsers() {
          return userRepository.findAll();
     }
    
      public User createUser(User user) {
          return userRepository.save(user);
      }
    }

8. Develop the User Controller

  • Create a folder controller and a class UserController.java:
    package com.microservices.user_service.controller;
    
    import com.microservices.user_service.model.User;
    import com.microservices.user_service.service.UserService;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        private final UserService userService;
    
        public UserController(UserService userService) {
            this.userService = userService;
        }
    
        @GetMapping
        public List<User> getAllUsers() {
            return userService.getAllUsers();
        }
    
        @PostMapping
        public ResponseEntity<User> createUser(@RequestBody User user) {
            User savedUser = userService.createUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(savedUser);
        }
    }

9. Run the Application

  • Open the Spring Boot Dashboard in VS Code, locate UserService, and start it.
  • Let us now run our application. We can do that with Maven was well.
mvn spring-boot:run
  • Check if UserService is running on port 8081 by visiting http://localhost:8081/api/users.

10. Create MySQL Database for UserService

  • Open MySQL and create a database for the UserService:
    CREATE DATABASE user_db;

11. Test the UserService GET Endpoint using Postman

  • Open Postman and follow these steps:
    1. Create a new request: Click New > HTTP Request.
    2. Set the request method: Select GET from the dropdown.
    3. Enter the URL: http://localhost:8081/api/users.
    4. Send the request: Click Send.
    5. Verify the response: If there are users in the database, you’ll see them in the response. If the database is empty, an empty array [] will be returned.

12. Containerize UserService with Docker

  • In the user-service directory, create a Dockerfile:
    FROM openjdk:17
    EXPOSE 8081
    ADD target/user-service-0.0.1-SNAPSHOT.jar user-service.jar
    ENTRYPOINT ["java", "-jar", "user-service.jar"]
  • Do a build
    ./mvnw clean package   # Linux / Mac
  • Build the Docker image for UserService:
    sudo docker build -t user-service .

13. Create Docker Compose for MySQL

  • In the Microservices directory, create docker-compose.yml:

    version: '3.1'
    services:
    mysql:
        image: mysql:5.7
        environment:
            MYSQL_ROOT_PASSWORD: Test1234!
            MYSQL_DATABASE: user_db
        ports:
            - "3306:3306"
    
    user-service:
        build: ./UserService/user-service
        environment:
            SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/user_db
            SPRING_DATASOURCE_USERNAME: root
            SPRING_DATASOURCE_PASSWORD: Test1234!
            SPRING_JPA_HIBERNATE_DDL_AUTO: update
        ports:
            - "8081:8081"
        depends_on:
            - mysql
       MicroservicesProject/
       ├── UserService/
       │   ├── src/
       │   ├── Dockerfile
       │   └── ...
       ├── ProductService/
       │   ├── src/
       │   ├── Dockerfile
       │   └── ...
       ├── docker-compose.yml
       └── ...

14. Run Docker Compose

  • Start the containers:
    docker-compose up --build

15. Test UserService with Dockerized MySQL

  • Restart the UserService application and test GET and POST endpoints again in Postman.

16. Discuss Best Practices

  • Discuss the importance of separating concerns by having each microservice manage its own data and configuration independently.

17. Summary of Lab

  • Summarize the tasks completed in Lab 1:
    • Created a basic microservice with Spring Boot (UserService).
    • Configured MySQL as the database.
    • Containerized UserService and MySQL using Docker.

Extra Exercise (20 minutes):

  1. Customizing the User Entity:

    • Add additional fields to the User entity, such as address, phoneNumber, and dateOfBirth.
    • Update the application properties as needed to support these fields.
  2. Testing Enhanced Endpoints:

    • Extend the UserController by adding an endpoint to retrieve a single user by ID (e.g., GET /api/users/{id}).
    • Test this endpoint using Postman.
  3. Practicing Docker Commands:

    • Use Docker commands to stop, start, and view the logs of the running UserService container.
    • Test restarting it and observe the application logs for any issues.