├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── img └── hexagonal-architecture.png └── src ├── main ├── java │ └── nd │ │ └── jar │ │ └── springhexboot │ │ ├── App.java │ │ ├── adapter │ │ ├── in │ │ │ └── http │ │ │ │ ├── EventDto.java │ │ │ │ ├── EventDtoMapper.java │ │ │ │ └── EventsController.java │ │ └── out │ │ │ ├── cache │ │ │ └── RedisCacheAdapter.java │ │ │ ├── kafka │ │ │ ├── KafkaAdapter.java │ │ │ └── KafkaConfiguration.java │ │ │ └── persistence │ │ │ ├── EventEntity.java │ │ │ ├── EventEntityMapper.java │ │ │ ├── EventPersistenceAdapter.java │ │ │ └── EventRepository.java │ │ └── application │ │ ├── domain │ │ ├── model │ │ │ └── Event.java │ │ └── service │ │ │ └── EventService.java │ │ └── port │ │ ├── in │ │ ├── FindEventsUseCase.java │ │ └── PushEventUseCase.java │ │ └── out │ │ ├── ExternalStorage.java │ │ ├── GetEventPort.java │ │ └── GetEventsPort.java └── resources │ └── application.yml └── test └── java └── nd └── jar └── springhexboot ├── TestApp.java └── TestContainersConfiguration.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | 6 | ### STS ### 7 | .apt_generated 8 | .classpath 9 | .factorypath 10 | .project 11 | .settings 12 | .springBeans 13 | .sts4-cache 14 | 15 | ### IntelliJ IDEA ### 16 | .idea 17 | *.iws 18 | *.iml 19 | *.ipr 20 | 21 | ### NetBeans ### 22 | /nbproject/private/ 23 | /nbbuild/ 24 | /dist/ 25 | /nbdist/ 26 | /.nb-gradle/ 27 | 28 | ### VS Code ### 29 | .vscode/ 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot Hexagonal 2 | Project shows, how to use hexagonal architecture in your spring boot applications 3 | 4 | ![Hexagonal Architecture](img/hexagonal-architecture.png) 5 | 6 | 7 | ## Implemented integrations: 8 | * Mysql (Spring Data JPA) 9 | * Redis (Spring Data Redis) 10 | 11 | 12 | ## Prerequisites 13 | 14 | * JDK 17 15 | * this project uses Lombok, so enable annotation processing in your IDE 16 | * this project uses Testcontainers, so run Docker on your local machine 17 | 18 | ## Getting Started 19 | `gradle testBootRun` 20 | 21 | ## Project Structure 22 | ``` 23 | └──com/ 24 | └── yourcompany/ 25 | ├── adapter/ # Adapter logic 26 | │ ├── in/ # Incoming requests adapters 27 | │ │ └── http/ 28 | │ └── out/ # Outgoing requests adapters 29 | │ ├── cache/ 30 | │ ├── kafka/ 31 | │ └── persistense/ 32 | ├── application # Core logic 33 | │ ├── domain/ 34 | │ │ ├── model/ 35 | │ │ └── service/ 36 | │ └── port/ # Core logic API 37 | │ ├── in/ 38 | │ └── out/ 39 | └── common/ # Neither business logic nor adapters 40 | ``` 41 | 42 | ## See More 43 | 44 | * [Гексагональная Архитектура и Spring Boot](https://habr.com/ru/articles/795127/) 45 | * Forked and inspired by [hombergs/buckpal](https://github.com/thombergs/buckpal) 46 | * [YouTube: Рустам Ахметов — Архитектура приложения и ошибки проектирования](https://www.youtube.com/watch?v=X6QdWTE1HHw&t=2194s&ab_channel=JPoint%2CJoker%D0%B8JUGru) 47 | * [Hexagonal Architecture with Java and Spring](https://reflectoring.io/spring-hexagonal/) 48 | * [Building a Multi-Module Spring Boot Application with Gradle](https://reflectoring.io/spring-boot-gradle-multi-module/) 49 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '3.2.2' 3 | id 'io.spring.dependency-management' version '1.1.4' 4 | id 'java' 5 | } 6 | 7 | 8 | group = 'nd.jar' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = 17 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 19 | implementation "org.springframework.boot:spring-boot-starter-data-jpa" 20 | // implementation "org.springframework.boot:spring-boot-starter-security" 21 | implementation 'org.springframework.boot:spring-boot-starter-validation' 22 | implementation "org.springframework.boot:spring-boot-starter-data-redis" 23 | implementation 'org.springframework.kafka:spring-kafka' 24 | 25 | implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.1.0' 26 | 27 | implementation 'mysql:mysql-connector-java:8.0.33' 28 | 29 | 30 | compileOnly 'org.projectlombok:lombok' 31 | annotationProcessor 'org.projectlombok:lombok' 32 | 33 | implementation 'org.mapstruct:mapstruct:1.5.5.Final' 34 | annotationProcessor 'org.mapstruct:mapstruct-processor:1.5.5.Final' 35 | 36 | 37 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 38 | testImplementation 'org.springframework.boot:spring-boot-testcontainers' 39 | testImplementation "org.testcontainers:mysql:1.19.0" 40 | testImplementation "org.testcontainers:kafka:1.19.5" 41 | testImplementation "com.redis:testcontainers-redis:2.0.1" 42 | 43 | } 44 | 45 | test { 46 | useJUnitPlatform() 47 | } 48 | 49 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nd-jar/spring-boot-hexagonal/f874270a10896eba5ff036fe5b2a40ae2b1e4e35/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /img/hexagonal-architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nd-jar/spring-boot-hexagonal/f874270a10896eba5ff036fe5b2a40ae2b1e4e35/img/hexagonal-architecture.png -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/App.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class App { 8 | public static void main(String[] args) { 9 | SpringApplication.run(App.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/in/http/EventDto.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.in.http; 2 | 3 | public record EventDto( 4 | String id, 5 | String name, 6 | String description, 7 | String from 8 | ){} -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/in/http/EventDtoMapper.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.in.http; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | import org.mapstruct.Mapper; 5 | 6 | @Mapper(componentModel = "spring") 7 | public interface EventDtoMapper { 8 | EventDto toDto(Event domain); 9 | Event toDomainModel(EventDto dto); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/in/http/EventsController.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.in.http; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import nd.jar.springhexboot.application.port.in.FindEventsUseCase; 5 | import nd.jar.springhexboot.application.port.in.PushEventUseCase; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PathVariable; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.util.Map; 13 | 14 | import static java.util.stream.Collectors.toMap; 15 | 16 | @RestController("/events") 17 | @RequiredArgsConstructor 18 | public class EventsController { 19 | private final EventDtoMapper eventDtoMapper; 20 | private final FindEventsUseCase findEventsUseCase; 21 | private final PushEventUseCase pushEventUseCase; 22 | 23 | @PostMapping 24 | ResponseEntity push(EventDto eventDto) { 25 | pushEventUseCase.push(eventDtoMapper.toDomainModel(eventDto)); 26 | return ResponseEntity.ok().build(); 27 | } 28 | 29 | @GetMapping("/{id}") 30 | Map get(@PathVariable("id") String id) { 31 | return findEventsUseCase.find(id).entrySet() 32 | .stream().collect(toMap(Map.Entry::getKey, entry -> eventDtoMapper.toDto(entry.getValue()))); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/cache/RedisCacheAdapter.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.cache; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.log4j.Log4j2; 7 | import nd.jar.springhexboot.application.domain.model.Event; 8 | import nd.jar.springhexboot.application.port.out.GetEventPort; 9 | import nd.jar.springhexboot.application.port.out.ExternalStorage; 10 | import org.springframework.data.redis.core.StringRedisTemplate; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.Optional; 14 | 15 | @Service 16 | @Log4j2 17 | @RequiredArgsConstructor 18 | public class RedisCacheAdapter implements ExternalStorage, GetEventPort { 19 | private final StringRedisTemplate stringRedisTemplate; 20 | private final ObjectMapper om; 21 | @Override 22 | public boolean push(Event event) { 23 | try { 24 | stringRedisTemplate.opsForValue().set(event.id(), om.writeValueAsString(event)); 25 | } catch (JsonProcessingException e) { 26 | log.error("Error while processing json", e); 27 | return false; 28 | } 29 | return true; 30 | } 31 | 32 | @Override 33 | public Optional find(String id) { 34 | final var stringResult = stringRedisTemplate.opsForValue().get(id); 35 | try { 36 | final var result = om.readValue(stringResult, Event.class); 37 | return Optional.of(result); 38 | } catch (JsonProcessingException e) { 39 | log.error("Error while processing json", e); 40 | return Optional.empty(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/kafka/KafkaAdapter.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.kafka; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.log4j.Log4j2; 7 | import nd.jar.springhexboot.application.domain.model.Event; 8 | import nd.jar.springhexboot.application.port.out.ExternalStorage; 9 | import org.springframework.kafka.core.KafkaTemplate; 10 | import org.springframework.stereotype.Service; 11 | 12 | import java.util.Optional; 13 | 14 | @Log4j2 15 | @Service 16 | @RequiredArgsConstructor 17 | public class KafkaAdapter implements ExternalStorage { 18 | private final KafkaTemplate template; 19 | private final ObjectMapper om; 20 | 21 | @Override 22 | public boolean push(Event event) { 23 | log.info("KAFKA: Pushing event with id=`{}`", event.id()); 24 | try { 25 | template.send("events", event.id(), om.writeValueAsString(event)); 26 | } catch (JsonProcessingException e) { 27 | log.error("Error while processing json", e); 28 | return false; 29 | } 30 | log.info("KAFKA: Pushed event with id=`{}`", event.id()); 31 | return true; 32 | } 33 | 34 | @Override 35 | public Optional find(String id) { 36 | log.error("Getting messages by id in kafka is not implemented"); 37 | return Optional.empty(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/kafka/KafkaConfiguration.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.kafka; 2 | 3 | import org.apache.kafka.clients.admin.NewTopic; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.kafka.config.TopicBuilder; 7 | 8 | @Configuration 9 | public class KafkaConfiguration { 10 | @Bean 11 | public NewTopic topic() { 12 | return TopicBuilder.name("events") 13 | .partitions(10) 14 | .replicas(1) 15 | .build(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/persistence/EventEntity.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.persistence; 2 | 3 | import jakarta.persistence.*; 4 | import lombok.*; 5 | 6 | @Entity 7 | @Table 8 | @Getter 9 | @Setter 10 | @ToString 11 | @RequiredArgsConstructor 12 | public class EventEntity { 13 | @Id 14 | private String id; 15 | 16 | private String name; 17 | 18 | private String description; 19 | 20 | @Column(name = "`from`") 21 | private String from; 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/persistence/EventEntityMapper.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.persistence; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | import org.mapstruct.Mapper; 5 | 6 | @Mapper(componentModel = "spring") 7 | public interface EventEntityMapper { 8 | Event toDomainModel(EventEntity entity); 9 | EventEntity toEntity(Event domainModel); 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/persistence/EventPersistenceAdapter.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.persistence; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import nd.jar.springhexboot.application.domain.model.Event; 5 | import nd.jar.springhexboot.application.port.out.ExternalStorage; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.Optional; 9 | 10 | @RequiredArgsConstructor 11 | @Service 12 | public class EventPersistenceAdapter implements ExternalStorage { 13 | private final EventRepository eventRepository; 14 | private final EventEntityMapper accountMapper; 15 | 16 | @Override 17 | public boolean push(Event event) { 18 | eventRepository.save(accountMapper.toEntity(event)); 19 | return true; 20 | } 21 | 22 | @Override 23 | public Optional find(String id) { 24 | return eventRepository.findById(id).map(accountMapper::toDomainModel); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/adapter/out/persistence/EventRepository.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.adapter.out.persistence; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface EventRepository extends JpaRepository {} 6 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/domain/model/Event.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.domain.model; 2 | 3 | public record Event( 4 | String id, 5 | String name, 6 | String description, 7 | String from 8 | ){} -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/domain/service/EventService.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.domain.service; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import nd.jar.springhexboot.application.domain.model.Event; 5 | import nd.jar.springhexboot.application.port.in.FindEventsUseCase; 6 | import nd.jar.springhexboot.application.port.in.PushEventUseCase; 7 | import nd.jar.springhexboot.application.port.out.ExternalStorage; 8 | import org.springframework.stereotype.Service; 9 | 10 | import java.util.Map; 11 | 12 | import static java.util.stream.Collectors.toMap; 13 | 14 | @Service 15 | @RequiredArgsConstructor 16 | public class EventService implements PushEventUseCase, FindEventsUseCase { 17 | private final Map storages; 18 | @Override 19 | public boolean push(Event event) { 20 | return storages.values().stream().map(sub -> sub.push(event)) 21 | .anyMatch(result -> !result); 22 | } 23 | 24 | @Override 25 | public Map find(String eventId) { 26 | return storages.entrySet().stream() 27 | .collect(toMap(Map.Entry::getKey, entry -> entry.getValue().find(eventId))).entrySet().stream() 28 | .filter(entry -> entry.getValue().isPresent()) 29 | .collect(toMap(Map.Entry::getKey, entry -> entry.getValue().get())); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/port/in/FindEventsUseCase.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.port.in; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | 5 | import java.util.Map; 6 | 7 | public interface FindEventsUseCase { 8 | Map find(String eventId); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/port/in/PushEventUseCase.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.port.in; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | 5 | public interface PushEventUseCase { 6 | boolean push(Event event); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/port/out/ExternalStorage.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.port.out; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | 5 | import java.util.Optional; 6 | 7 | public interface ExternalStorage { 8 | boolean push(Event event); 9 | Optional find(String id); 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/port/out/GetEventPort.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.port.out; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | import org.springframework.data.domain.Pageable; 5 | 6 | import java.util.List; 7 | import java.util.Optional; 8 | 9 | public interface GetEventPort { 10 | Optional find(String id); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/nd/jar/springhexboot/application/port/out/GetEventsPort.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot.application.port.out; 2 | 3 | import nd.jar.springhexboot.application.domain.model.Event; 4 | import org.springframework.data.domain.Pageable; 5 | 6 | import java.util.List; 7 | 8 | public interface GetEventsPort { 9 | List getAll(Pageable pageable); //todo: Pageable is part of spring-data. Need to remove from here. 10 | } 11 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | jpa: 3 | hibernate: 4 | ddl-auto: create 5 | show-sql: true 6 | logging: 7 | level: 8 | org.springframework.web.reactive.function.client.ExchangeFunctions: debug 9 | org: 10 | hibernate: 11 | internal: 12 | SessionImpl: DEBUG 13 | SQL: INFO 14 | type: TRACE 15 | loader: 16 | hql: TRACE 17 | engine: 18 | transaction: 19 | internal: 20 | TransactionImpl: DEBUG 21 | -------------------------------------------------------------------------------- /src/test/java/nd/jar/springhexboot/TestApp.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | 5 | public class TestApp { 6 | public static void main(String[] args) { 7 | SpringApplication.from(App::main) 8 | .with(TestContainersConfiguration.class) 9 | .run(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/nd/jar/springhexboot/TestContainersConfiguration.java: -------------------------------------------------------------------------------- 1 | package nd.jar.springhexboot; 2 | 3 | import com.redis.testcontainers.RedisContainer; 4 | import org.springframework.boot.test.context.TestConfiguration; 5 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 6 | import org.springframework.context.annotation.Bean; 7 | import org.testcontainers.containers.KafkaContainer; 8 | import org.testcontainers.containers.MySQLContainer; 9 | import org.testcontainers.utility.DockerImageName; 10 | 11 | @TestConfiguration 12 | public class TestContainersConfiguration { 13 | @Bean 14 | @ServiceConnection 15 | MySQLContainer mySQLContainer() { 16 | return new MySQLContainer<>("mysql:5.7.39"); 17 | } 18 | 19 | @Bean 20 | @ServiceConnection(name = "redis") 21 | RedisContainer redisContainer(){ 22 | return new RedisContainer(DockerImageName.parse("redis:6.2.6")); 23 | } 24 | 25 | @Bean 26 | @ServiceConnection 27 | KafkaContainer kafka() { 28 | return new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1")); 29 | } 30 | 31 | 32 | } 33 | --------------------------------------------------------------------------------