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.
- 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.
- Inside the
MicroservicesProject
folder, create three subdirectories:UserService
ProductService
OrderService
- 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.
- Group Id:
- Save the project in the
UserService
folder.
<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>
- In the
UserService/src/main/resources
folder, openapplication.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
- In the
com.microservices.user_service
package, create a foldermodel
and a new class calledUser.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; } }
- In the same package, create a folder
repository
and a new interfaceUserRepository.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> { }
-
Create a folder
service
and a classUserService.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); } }
- Create a folder
controller
and a classUserController.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); } }
- 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 visitinghttp://localhost:8081/api/users
.
- Open MySQL and create a database for the UserService:
CREATE DATABASE user_db;
- Open Postman and follow these steps:
- Create a new request: Click New > HTTP Request.
- Set the request method: Select GET from the dropdown.
- Enter the URL:
http://localhost:8081/api/users
. - Send the request: Click Send.
- 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.
- In the
user-service
directory, create aDockerfile
: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 .
-
In the
Microservices
directory, createdocker-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
└── ...
- Start the containers:
docker-compose up --build
- Restart the
UserService
application and testGET
andPOST
endpoints again in Postman.
- Discuss the importance of separating concerns by having each microservice manage its own data and configuration independently.
- 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.
-
Customizing the User Entity:
- Add additional fields to the
User
entity, such asaddress
,phoneNumber
, anddateOfBirth
. - Update the application properties as needed to support these fields.
- Add additional fields to the
-
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.
- Extend the
-
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.
- Use Docker commands to stop, start, and view the logs of the running