mashkova_margarita_lab_3 ready

This commit is contained in:
rita 2023-12-14 09:39:03 +04:00
parent bbeb924b57
commit 45b0dc6f0a
37 changed files with 1496 additions and 0 deletions

View File

@ -0,0 +1,206 @@
# Лабораторная работа №3
## ПИбд-42 Машкова Маргарита
## Задание
1. Создать 2 микросервиса, реализующих CRUD на связанных сущностях.
2. Реализовать механизм синхронного обмена сообщениями между микросервисами.
3. Реализовать шлюз на основе прозрачного прокси-сервера nginx.
## Запуск программы
В директории с файлом `docker-compose.yml` выполнить команду:
```
docker-compose up -d
```
## Описание работы программы
### 2 микросервиса, реализующих CRUD на связанных сущностях:
#### Описание сущностей:
- `Groupe` - группа в университете, содержит 2 атрибута: id и name.
P.S. Слово `group` специально написано неправильно, т.к. такое слово зарезервиравано в СУБД :)
- `Student` - студент, сущность содержит 4 атрибута: id, name, surname, groupeId.
Соответственно сущности связаны один (группа) - ко многим (студенты).
Данные микросервисы, выполняющие CRUD операции над сущностями, реализованы при помощи фреймворка `spring`.
### Реализация механизма синхронного обмена сообщениями между микросервисами:
Реализуется при помощи `RestTemplate`. При получении информации о студенте или о всех студентах отправляется GET запрос
к сервису `groupe-service`, чтобы получить информацию о группе, в которой учится студент.
```
private final RestTemplate restTemplate = new RestTemplate();
private final String URL = "http://groupe-service:8080/groupe/";
public StudentInfoDto findStudentInfo(Integer id){
Student student = studentRepository.findById(id)
.orElseThrow(() -> new RuntimeException(String.format("Student with id %s was not found", id)));
GroupeInfoDto group = restTemplate.getForObject(URL + student.getGroupeId(), GroupeInfoDto.class);
StudentInfoDto studentInfoDto = new StudentInfoDto();
studentInfoDto.setId(id);
studentInfoDto.setName(student.getName());
studentInfoDto.setSurname(student.getSurname());
studentInfoDto.setGroupeInfoDto(group);
return studentInfoDto;
}
```
### Файл конфигурации `docker-compose.yml`:
Для обеспечения работы прокси-сервера nginx в качестве шлюза, необходимо чтобы все управляемые им сервисы находились
в одной сети типа "мост":
```
networks:
my-network:
driver: bridge
```
#### Настройка сервисов:
Для сервиса БД `db-university` используется образ postgres. Также указывается порт взаимодействия,
переменные окружения - логин, пароль для учетной записи в postgres и имя БД. Сервис добавлятся в созданную сеть.
Опция `restart: always` означает, что docker-compose перезапустит контейнер, если тот вдруг остановится.
```
db-university:
image: postgres:latest
container_name: db-university
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: admin
POSTGRES_USER: admin
POSTGRES_DB: university
restart: always
networks:
- my-network
```
Для сервисов `groupe-service` и `student-service` используются образы приложений, созданные при помощи Dockerfile.
Также указывается порт взаимодействия, зависимость от сервиса БД (контейнер микросервиса запускается только
после запуска контейнера БД).
Сервис добавлятся в созданную сеть.
Опция `restart: always` означает, что docker-compose перезапустит контейнер, если тот вдруг остановится.
```
groupe-service:
build:
context: .
dockerfile: ./groupe-service/Dockerfile
container_name: groupe-service
ports:
- 8080:8080
restart: always
depends_on:
- db-university
networks:
- my-network
student-service:
build:
context: .
dockerfile: ./student-service/Dockerfile
container_name: student-service
ports:
- 8081:8081
restart: always
depends_on:
- db-university
networks:
- my-network
```
### Dockerfile сервиса `groupe-service`:
Используется базовый образ openjdk:17-jdk. Задается рабочая директория /app. В нее копируется jar файл приложения.
Указывается порт, на котором работает приложение. Запуск программы осуществляется посредством запуска jar файла.
```
FROM openjdk:17-jdk
WORKDIR /app
COPY ./groupe-service/build/libs/groupe-service-1.0-SNAPSHOT.jar /app/groupe-service-1.0-SNAPSHOT.jar
EXPOSE 8080
CMD ["java", "-jar", "groupe-service-1.0-SNAPSHOT.jar"]
```
### Dockerfile сервиса `student-service`:
Структура аналогична Dockerfile сервиса `groupe-service`.
```
FROM openjdk:17-jdk
WORKDIR /app
COPY ./student-service/build/libs/student-service-1.0-SNAPSHOT.jar /app/student-service-1.0-SNAPSHOT.jar
EXPOSE 8081
CMD ["java", "-jar", "student-service-1.0-SNAPSHOT.jar"]
```
### Реализация шлюза на основе прозрачного прокси-сервера nginx:
Для сервиса `nginx` используется образ nginx, указывается порт взаимодействия.
`volumes` указывает, что при запуске контейнера, локальный файл конфигураций nginx.conf следует поместить вместо
стандартного файла конфигураций nginx, а `depends_on` указывает, что данный прокси-сервер зависит от обоих сервисов
и разворачивается только после их запуска.
```
nginx:
image: nginx
container_name: nginx
ports:
- "80:80"
networks:
- my-network
volumes:
- ./nginx-conf:/etc/nginx/conf.d
depends_on:
- groupe-service
- student-service
```
### Файл конфигурации `nginx.conf`:
Данная конфигурация позволяет перенаправлять запросы, начинающиеся с `/groupe-service/` на сервер
groupe-service на порту 8080, а запросы, начинающиеся с `/student-service/`, на сервер student-service на порту 8081.
Заголовки запроса также передаются и устанавливаются соответствующие значения для Host и X-Forwarded-Prefix.
Заголовок Host будет установлен в значение $host, заголовок X-Forwarded-Prefix - в значение `/student-service` или
`/groupe-service`.
```
server {
listen 80;
location /groupe-service/ {
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Prefix '/groupe-service';
proxy_pass http://groupe-service:8080/;
}
location /student-service/ {
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Prefix '/student-service';
proxy_pass http://student-service:8081/;
}
}
```
## Запуск сервисов
### Результат выполнения команды `docker-compose up -d`:
![Вывод в консоли](build_images.png)
### Созданные образы:
![Созданные образы](images.png)
### Созданные контейнеры:
![Созданные контейнеры](containers.png)
### Результаты синхронного обмена сообщениями между микросервисами:
При получения списка студентов, сервис `student-service` обращается к сервису `groupe-service`,
чтобы отобразить данные группы.
![results](results.png)
Ссылка на видео:
https://youtu.be/BCF0Lxc6veo

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -0,0 +1,58 @@
version: '3'
networks:
my-network:
driver: bridge
services:
db-university:
image: postgres:latest
container_name: db-university
ports:
- 5432:5432
environment:
POSTGRES_PASSWORD: admin
POSTGRES_USER: admin
POSTGRES_DB: university
restart: always
networks:
- my-network
groupe-service:
build:
context: .
dockerfile: ./groupe-service/Dockerfile
container_name: groupe-service
ports:
- 8080:8080
restart: always
depends_on:
- db-university
networks:
- my-network
student-service:
build:
context: .
dockerfile: ./student-service/Dockerfile
container_name: student-service
ports:
- 8081:8081
restart: always
depends_on:
- db-university
networks:
- my-network
nginx:
image: nginx
container_name: nginx
ports:
- "80:80"
networks:
- my-network
volumes:
- ./nginx-conf:/etc/nginx/conf.d
depends_on:
- groupe-service
- student-service

View File

@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -0,0 +1,7 @@
FROM openjdk:17-jdk
WORKDIR /app
COPY ./groupe-service/build/libs/groupe-service-1.0-SNAPSHOT.jar /app/groupe-service-1.0-SNAPSHOT.jar
EXPOSE 8080
CMD ["java", "-jar", "groupe-service-1.0-SNAPSHOT.jar"]

View File

@ -0,0 +1,37 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.0'
id 'io.spring.dependency-management' version '1.1.0'
}
group 'org.example'
version '1.0-SNAPSHOT'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.3'
implementation 'org.mapstruct:mapstruct:1.5.3.Final'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.3.Final'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,2 @@
rootProject.name = 'groupe-service'

View File

@ -0,0 +1,11 @@
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GroupeApplication {
public static void main(String[] args) {
SpringApplication.run(GroupeApplication.class, args);
}
}

View File

@ -0,0 +1,45 @@
package org.example.controller;
import org.example.dto.GroupeDto;
import org.example.mapper.GroupeMapper;
import org.example.service.GroupeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/groupe")
public class GroupeController {
@Autowired
private GroupeService groupeService;
@Autowired
private GroupeMapper groupeMapper;
@GetMapping("/")
public List<GroupeDto> getGroups() {
return groupeService.findAllGroups().stream()
.map(groupe -> groupeMapper.toGroupeDto(groupe))
.toList();
}
@GetMapping("/{id}")
public GroupeDto getGroup(@PathVariable Integer id){
return groupeMapper.toGroupeDto(groupeService.findGroup(id));
}
@PostMapping
public GroupeDto createGroup(@RequestBody GroupeDto groupeDto){
return groupeMapper.toGroupeDto(groupeService.addGroup(groupeDto.getId(), groupeDto.getName()));
}
@PutMapping("/{id}")
public GroupeDto editGroup(@RequestBody GroupeDto groupeDto){
return groupeMapper.toGroupeDto(groupeService.updateGroup(groupeDto.getId(), groupeDto.getName()));
}
@DeleteMapping("/{id}")
public void deleteGroup(@PathVariable Integer id){
groupeService.deleteGroup(id);
}
}

View File

@ -0,0 +1,9 @@
package org.example.dto;
import lombok.Data;
@Data
public class GroupeDto {
private Integer id;
private String name;
}

View File

@ -0,0 +1,12 @@
package org.example.mapper;
import org.example.dto.GroupeDto;
import org.example.model.Groupe;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface GroupeMapper {
Groupe fromGroupeDto(GroupeDto groupeDto);
GroupeDto toGroupeDto(Groupe groupe);
}

View File

@ -0,0 +1,20 @@
package org.example.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.*;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Entity
public class Groupe {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NonNull
private String name;
}

View File

@ -0,0 +1,7 @@
package org.example.repository;
import org.example.model.Groupe;
import org.springframework.data.jpa.repository.JpaRepository;
public interface GroupeRepository extends JpaRepository<Groupe, Integer> {
}

View File

@ -0,0 +1,47 @@
package org.example.service;
import org.example.model.Groupe;
import org.example.repository.GroupeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class GroupeService {
@Autowired
private GroupeRepository groupeRepository;
@Transactional(readOnly = true)
public List<Groupe> findAllGroups(){
return groupeRepository.findAll();
}
@Transactional(readOnly = true)
public Groupe findGroup(Integer id){
final Optional<Groupe> group = groupeRepository.findById(id);
return group.orElseThrow(() -> new RuntimeException(String.format("Group with id %s was not found", id)));
}
@Transactional
public Groupe addGroup(Integer id, String name){
Groupe group = new Groupe(id, name);
return groupeRepository.save(group);
}
@Transactional
public Groupe updateGroup(Integer id, String name){
final Groupe group = findGroup(id);
group.setName(name);
return groupeRepository.save(group);
}
@Transactional
public Groupe deleteGroup(Integer id){
Groupe group = findGroup(id);
groupeRepository.delete(group);
return group;
}
}

View File

@ -0,0 +1,11 @@
server:
port: "8080"
spring:
datasource:
url: jdbc:postgresql://db-university:5432/university
username: admin
password: admin
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,18 @@
server {
listen 80;
location /groupe-service/ {
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Prefix '/groupe-service';
proxy_pass http://groupe-service:8080/;
}
location /student-service/ {
proxy_pass_request_headers on;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Prefix '/student-service';
proxy_pass http://student-service:8081/;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View File

@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -0,0 +1,7 @@
FROM openjdk:17-jdk
WORKDIR /app
COPY ./student-service/build/libs/student-service-1.0-SNAPSHOT.jar /app/student-service-1.0-SNAPSHOT.jar
EXPOSE 8081
CMD ["java", "-jar", "student-service-1.0-SNAPSHOT.jar"]

View File

@ -0,0 +1,37 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.0'
id 'io.spring.dependency-management' version '1.1.0'
}
group 'org.example'
version '1.0-SNAPSHOT'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.3'
implementation 'org.mapstruct:mapstruct:1.5.3.Final'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.3.Final'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,2 @@
rootProject.name = 'student-service'

View File

@ -0,0 +1,11 @@
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}

View File

@ -0,0 +1,49 @@
package org.example.controller;
import org.example.dto.StudentDto;
import org.example.dto.StudentInfoDto;
import org.example.mapper.StudentMapper;
import org.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private StudentMapper studentMapper;
@GetMapping("/")
public List<StudentInfoDto> getStudents(){
return studentService.findAllStudents();
}
@GetMapping("/{id}")
public StudentInfoDto getStudent(@PathVariable Integer id){
return studentService.findStudentInfo(id);
}
@PostMapping
public StudentDto createStudent(@RequestBody StudentDto studentDto){
return studentMapper.toStudentDto(
studentService.addStudent(studentDto.getId(), studentDto.getName(), studentDto.getSurname(),
studentDto.getGroupeId()));
}
@PutMapping("/{id}")
public StudentDto editStudent(@RequestBody StudentDto studentDto){
return studentMapper.toStudentDto(
studentService.updateStudent(studentDto.getId(), studentDto.getName(), studentDto.getSurname(),
studentDto.getGroupeId()));
}
@DeleteMapping("/{id}")
public void deleteStudent(@PathVariable Integer id){
studentService.deleteStudent(id);
}
}

View File

@ -0,0 +1,9 @@
package org.example.dto;
import lombok.Data;
@Data
public class GroupeInfoDto {
private Integer id;
private String name;
}

View File

@ -0,0 +1,11 @@
package org.example.dto;
import lombok.Data;
@Data
public class StudentDto {
private Integer id;
private String name;
private String surname;
private Integer groupeId;
}

View File

@ -0,0 +1,11 @@
package org.example.dto;
import lombok.Data;
@Data
public class StudentInfoDto {
private Integer id;
private String name;
private String surname;
private GroupeInfoDto groupeInfoDto;
}

View File

@ -0,0 +1,12 @@
package org.example.mapper;
import org.example.dto.StudentDto;
import org.example.model.Student;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface StudentMapper {
Student fromStudentDto(StudentDto studentDto);
StudentDto toStudentDto(Student student);
}

View File

@ -0,0 +1,24 @@
package org.example.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.*;
import org.example.dto.GroupeInfoDto;
@Data
@NoArgsConstructor
@RequiredArgsConstructor
@AllArgsConstructor
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NonNull
private String name;
@NonNull
private String surname;
private Integer groupeId;
}

View File

@ -0,0 +1,7 @@
package org.example.repository;
import org.example.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentRepository extends JpaRepository<Student, Integer> {
}

View File

@ -0,0 +1,79 @@
package org.example.service;
import org.example.dto.GroupeInfoDto;
import org.example.dto.StudentInfoDto;
import org.example.model.Student;
import org.example.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
private final RestTemplate restTemplate = new RestTemplate();
private final String URL = "http://groupe-service:8080/groupe/";
@Transactional(readOnly = true)
public List<StudentInfoDto> findAllStudents(){
List <Student> students = studentRepository.findAll();
List <StudentInfoDto> studentsInfo = new ArrayList<>();
for (Student student : students) {
StudentInfoDto studentInfo = findStudentInfo(student.getId());
studentsInfo.add(studentInfo);
}
return studentsInfo;
}
@Transactional(readOnly = true)
public Student findStudent(Integer id){
final Optional<Student> student = studentRepository.findById(id);
return student.orElseThrow(() -> new RuntimeException(String.format("Student with id %s was not found", id)));
}
@Transactional(readOnly = true)
public StudentInfoDto findStudentInfo(Integer id){
Student student = studentRepository.findById(id)
.orElseThrow(() -> new RuntimeException(String.format("Student with id %s was not found", id)));
GroupeInfoDto group = restTemplate.getForObject(URL + student.getGroupeId(), GroupeInfoDto.class);
StudentInfoDto studentInfoDto = new StudentInfoDto();
studentInfoDto.setId(id);
studentInfoDto.setName(student.getName());
studentInfoDto.setSurname(student.getSurname());
studentInfoDto.setGroupeInfoDto(group);
return studentInfoDto;
}
@Transactional
public Student addStudent(Integer id, String name, String surname, Integer groupeId){
Student student = new Student(id, name, surname, groupeId);
return studentRepository.save(student);
}
@Transactional
public Student updateStudent(Integer id, String name, String surname, Integer groupeId){
Student student = findStudent(id);
student.setName(name);
student.setSurname(surname);
student.setGroupeId(groupeId);
return studentRepository.save(student);
}
@Transactional
public Student deleteStudent(Integer id){
Student student = findStudent(id);
studentRepository.delete(student);
return student;
}
}

View File

@ -0,0 +1,11 @@
server:
port: "8081"
spring:
datasource:
url: jdbc:postgresql://db-university:5432/university
username: admin
password: admin
driver-class-name: org.postgresql.Driver
jpa:
hibernate:
ddl-auto: update