This commit is contained in:
2023-02-22 09:44:56 +09:00
parent bc4a9a6482
commit 2b1d3757b3
100 changed files with 2697 additions and 77 deletions

View File

@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.7'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

View File

@@ -46,7 +46,7 @@ public class JwtTokenProvider {
long now = (new Date()).getTime();
// Access Token 생성
Date accessTokenExpiresIn = new Date(now + 86400000);
Date accessTokenExpiresIn = new Date(now + 18000);
String accessToken = Jwts.builder()
.setSubject(authentication.getName())
.claim("auth", authorities)
@@ -56,7 +56,7 @@ public class JwtTokenProvider {
// Refresh Token 생성
String refreshToken = Jwts.builder()
.setExpiration(new Date(now + 86400000)) // 86400000(24 * 60 * 60 * 1000) => 1일
.setExpiration(new Date(now + 18000)) // 86400000(24 * 60 * 60 * 1000) => 1일
.signWith(key, SignatureAlgorithm.HS256)
.compact();

37
core-service/.gitignore vendored Normal file
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/

39
core-service/build.gradle Normal file
View File

@@ -0,0 +1,39 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'com.kiz'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
bootJar {
enabled = false
}
jar {
enabled = true
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'com.fasterxml.jackson.core:jackson-core:2.14.2'
implementation 'com.fasterxml.jackson.core:jackson-annotations:2.14.2'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.14.2'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.2'
implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.14.2'
implementation 'com.fasterxml.jackson.module:jackson-module-parameter-names:2.14.2'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
core-service/gradlew vendored Normal file
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" "$@"

91
core-service/gradlew.bat vendored Normal file
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 @@
rootProject.name = 'core-service'

View File

@@ -0,0 +1,26 @@
package com.kiz.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface PersistenceAdapter {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}

View File

@@ -0,0 +1,26 @@
package com.kiz.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface UseCase {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}

View File

@@ -0,0 +1,26 @@
package com.kiz.common;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface WebAdapter {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
*/
@AliasFor(annotation = Component.class)
String value() default "";
}

View File

@@ -0,0 +1,92 @@
package com.kiz.event;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import com.kiz.event.exceptions.InvalidEventException;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public abstract class AggregateRoot {
protected String id;
protected String type;
protected long version;
protected final List<Event> changes = new ArrayList<>();
public AggregateRoot(final String id, final String aggregateType) {
this.id = id;
this.type = aggregateType;
}
public abstract void when(final Event event);
public void load(final List<Event> events) {
events.forEach(event -> {
this.validateEvent(event);
this.raiseEvent(event);
this.version++;
});
}
public void apply(final Event event) {
this.validateEvent(event);
event.setAggregateType(this.type);
when(event);
changes.add(event);
this.version++;
event.setVersion(this.version);
}
public void raiseEvent(final Event event) {
this.validateEvent(event);
event.setAggregateType(this.type);
when(event);
this.version++;
}
public void clearChanges() {
this.changes.clear();
}
public void toSnapshot() {
this.clearChanges();
}
private void validateEvent(final Event event) {
if (Objects.isNull(event) || !event.getAggregateId().equals(this.id))
throw new InvalidEventException(event.toString());
}
protected Event createEvent(String eventType, byte[] data, byte[] metadata) {
return Event.builder()
.aggregateId(this.getId())
.version(this.getVersion())
.aggregateType(this.getType())
.eventType(eventType)
.data(Objects.isNull(data) ? new byte[]{} : data)
.metaData(Objects.isNull(metadata) ? new byte[]{} : metadata)
.timeStamp(LocalDateTime.now())
.build();
}
@Override
public String toString() {
return "AggregateRoot{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
", version=" + version +
", changes=" + changes.size() +
'}';
}
}

View File

@@ -0,0 +1,20 @@
package com.kiz.event;
import java.util.Objects;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
public abstract class BaseEvent {
protected String aggregateId;
public BaseEvent(String aggregateId) {
Objects.requireNonNull(aggregateId);
if (aggregateId.isBlank()) throw new RuntimeException("BaseEvent aggregateId is required");
this.aggregateId = aggregateId;
}
}

View File

@@ -0,0 +1,19 @@
package com.kiz.event;
public final class Constants {
private Constants() {
}
public static final String AGGREGATE_ID = "aggregate_id";
public static final String SNAPSHOT_ID = "snapshot_id";
public static final String AGGREGATE_TYPE = "aggregate_type";
public static final String EVENT_TYPE = "event_type";
public static final String EVENT_ID = "event_id";
public static final String VERSION = "version";
public static final String DATA = "data";
public static final String METADATA = "metadata";
public static final String TIMESTAMP = "timestamp";
public static final String EVENTS = "events";
}

View File

@@ -0,0 +1,48 @@
package com.kiz.event;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Event {
private UUID id;
private String aggregateId;
private String eventType;
private String aggregateType;
private long version;
private byte[] data;
private byte[] metaData;
private LocalDateTime timeStamp;
public Event(String eventType, String aggregateType) {
this.id = UUID.randomUUID();
this.eventType = eventType;
this.aggregateType = aggregateType;
this.timeStamp = LocalDateTime.now();
}
@Override
public String toString() {
return "Event{" +
"id=" + id +
", aggregateId='" + aggregateId + '\'' +
", eventType='" + eventType + '\'' +
", aggregateType='" + aggregateType + '\'' +
", version=" + version + '\'' +
", timeStamp=" + timeStamp + '\'' +
", data=" + new String(data) + '\'' +
'}';
}
}

View File

@@ -0,0 +1,9 @@
package com.kiz.event;
import java.util.List;
public interface EventBus {
void publish(List<Event> events);
}

View File

@@ -0,0 +1,33 @@
package com.kiz.event;
import java.time.LocalDateTime;
import java.util.UUID;
import static com.kiz.event.Constants.EVENTS;
public class EventSourcingUtils {
private EventSourcingUtils() {
}
public static String getAggregateTypeTopic(final String aggregateType) {
return String.format("%s_%s", aggregateType, EVENTS);
}
public static <T extends AggregateRoot> Snapshot snapshotFromAggregate(final T aggregate) {
byte[] bytes = SerializerUtils.serializeToJsonBytes(aggregate);
return Snapshot.builder()
.id(UUID.randomUUID())
.aggregateId(aggregate.getId())
.aggregateType(aggregate.getType())
.version(aggregate.getVersion())
.data(bytes)
.timeStamp(LocalDateTime.now())
.build();
}
public static <T extends AggregateRoot> T aggregateFromSnapshot(final Snapshot snapshot, final Class<T> valueType) {
return SerializerUtils.deserializeFromJsonBytes(snapshot.getData(), valueType);
}
}

View File

@@ -0,0 +1,17 @@
package com.kiz.event;
import java.util.List;
public interface EventStoreDB {
void saveEvents(final List<Event> events);
List<Event> loadEvents(final String aggregateId, long version);
<T extends AggregateRoot> void save(final T aggregate);
<T extends AggregateRoot> T load(final String aggregateId, final Class<T> aggregateType);
Boolean exists(final String aggregateId);
}

View File

@@ -0,0 +1,7 @@
package com.kiz.event;
public interface Projection {
void when(Event event);
}

View File

@@ -0,0 +1,69 @@
package com.kiz.event;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
public final class SerializerUtils {
private static final ObjectMapper objectMapper = JsonMapper.builder()
.addModule(new ParameterNamesModule())
.addModule(new Jdk8Module())
.addModule(new JavaTimeModule())
.build();
private SerializerUtils() {
}
public static byte[] serializeToJsonBytes(final Object object) {
try {
return objectMapper.writeValueAsBytes(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static <T> T deserializeFromJsonBytes(final byte[] jsonBytes, final Class<T> valueType) {
try {
return objectMapper.readValue(jsonBytes, valueType);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static Event[] deserializeEventsFromJsonBytes(final byte[] jsonBytes) {
try {
return objectMapper.readValue(jsonBytes, Event[].class);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static HashMap<String, byte[]> deserializeEventsMetadata(final byte[] metaData) {
final var tr = new TypeReference<HashMap<String, byte[]>>() {
};
try {
return objectMapper.readValue(metaData, tr);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public static byte[] serializeEventsMetadata(final HashMap<String, byte[]> metaData) {
try {
final var valueAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(metaData);
return valueAsString.getBytes(StandardCharsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,40 @@
package com.kiz.event;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Snapshot {
private UUID id;
private String aggregateId;
private String aggregateType;
private byte[] data;
private byte[] metaData;
private long version;
private LocalDateTime timeStamp;
@Override
public String toString() {
return "Snapshot{" +
"id=" + id +
", aggregateId='" + aggregateId + '\'' +
", aggregateType='" + aggregateType + '\'' +
", data=" + data.length + " bytes" +
", metaData=" + metaData.length + " bytes" +
", version=" + version +
", timeStamp=" + timeStamp +
'}';
}
}

View File

@@ -0,0 +1,13 @@
package com.kiz.event.exceptions;
public class AggregateNotFoundException extends RuntimeException {
public AggregateNotFoundException() {
super();
}
public AggregateNotFoundException(String aggregateID) {
super("aggregate not found id:" + aggregateID);
}
}

View File

@@ -0,0 +1,12 @@
package com.kiz.event.exceptions;
public class InvalidEventException extends RuntimeException {
public InvalidEventException() {
}
public InvalidEventException(String message) {
super("invalid event: " + message);
}
}

View File

@@ -0,0 +1,12 @@
package com.kiz.event.exceptions;
public class InvalidEventTypeException extends RuntimeException {
public InvalidEventTypeException() {
}
public InvalidEventTypeException(String eventType) {
super("invalid event type: " + eventType);
}
}

View File

@@ -0,0 +1,33 @@
CREATE TABLE IF NOT EXISTS events
(
event_id CHAR(36) BINARY NOT NULL DEFAULT UUID(),
aggregate_id VARCHAR(250) NOT NULL CHECK ( aggregate_id <> '' ),
aggregate_type VARCHAR(250) NOT NULL CHECK ( aggregate_type <> '' ),
event_type VARCHAR(250) NOT NULL CHECK ( event_type <> '' ),
data LONGBLOB,
metadata LONGBLOB,
version BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (event_id),
UNIQUE KEY (aggregate_id, version),
KEY version_idx (version)
) ENGINE=INNODB ;
CREATE INDEX IF NOT EXISTS aggregate_id_aggregate_version_idx ON events (aggregate_id, version ASC);
CREATE TABLE IF NOT EXISTS snapshots
(
event_id CHAR(36) BINARY NOT NULL DEFAULT UUID(),
aggregate_id VARCHAR(250) NOT NULL CHECK ( aggregate_id <> '' ),
aggregate_type VARCHAR(250) NOT NULL CHECK ( aggregate_type <> '' ),
event_type VARCHAR(250) NOT NULL CHECK ( event_type <> '' ),
data LONGBLOB,
metadata LONGBLOB,
version BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (event_id),
UNIQUE KEY (aggregate_id, version),
KEY version_idx (version)
) ENGINE=INNODB ;
CREATE INDEX IF NOT EXISTS aggregate_id_aggregate_version_idx ON snapshots (aggregate_id, version);

View File

@@ -0,0 +1,42 @@
CREATE EXTENSION IF NOT EXISTS citext;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
DROP TABLE IF EXISTS events CASCADE;
DROP TABLE IF EXISTS snapshots CASCADE;
CREATE TABLE IF NOT EXISTS events
(
event_id UUID DEFAULT uuid_generate_v4(),
aggregate_id VARCHAR(250) NOT NULL CHECK ( aggregate_id <> '' ),
aggregate_type VARCHAR(250) NOT NULL CHECK ( aggregate_type <> '' ),
event_type VARCHAR(250) NOT NULL CHECK ( event_type <> '' ),
data BYTEA,
metadata BYTEA,
version SERIAL NOT NULL,
timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
UNIQUE (aggregate_id, version)
) PARTITION BY HASH (aggregate_id);
CREATE INDEX IF NOT EXISTS aggregate_id_aggregate_version_idx ON events USING btree (aggregate_id, version ASC);
CREATE TABLE IF NOT EXISTS events_partition_hash_1 PARTITION OF events
FOR VALUES WITH (MODULUS 3, REMAINDER 0);
CREATE TABLE IF NOT EXISTS events_partition_hash_2 PARTITION OF events
FOR VALUES WITH (MODULUS 3, REMAINDER 1);
CREATE TABLE IF NOT EXISTS events_partition_hash_3 PARTITION OF events
FOR VALUES WITH (MODULUS 3, REMAINDER 2);
CREATE TABLE IF NOT EXISTS snapshots
(
snapshot_id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
aggregate_id VARCHAR(250) UNIQUE NOT NULL CHECK ( aggregate_id <> '' ),
aggregate_type VARCHAR(250) NOT NULL CHECK ( aggregate_type <> '' ),
data BYTEA,
metadata BYTEA,
version SERIAL NOT NULL,
timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
UNIQUE (aggregate_id)
);
CREATE INDEX IF NOT EXISTS aggregate_id_aggregate_version_idx ON snapshots USING btree (aggregate_id, version);

View File

@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.7'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

View File

@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.7'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

View File

@@ -24,4 +24,4 @@ http://mindol.synology.me:8081/auth-service/welcome
### GET
http://mindol.synology.me:8081/member-service/members
Authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0MiIsImF1dGgiOiIiLCJleHAiOjE2NzIzMDI0MDJ9.Xa7HqBjG4adHNPL6zQudceBc9sfR727xk4Ld-gKFZMC
Authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0MiIsImF1dGgiOiIiLCJleHAiOjE2NzIyMTgwNjB9.zTxL2W3p2BP1IfGRL_KEhnDNLSt_ipr6Izh637hpI0M

View File

@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.7'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
@@ -28,10 +28,13 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'
implementation 'org.springframework.cloud:spring-cloud-starter-config'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-stream'
implementation 'org.springframework.cloud:spring-cloud-stream-binder-kafka'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.h2database:h2'

View File

@@ -3,7 +3,14 @@ package kiz.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import kiz.app.member.adapter.out.persistence.repository.MemberJpaRepository;
import kiz.app.member.adapter.out.persistence.repository.MemberMongoRepository;
@EnableJpaRepositories(basePackageClasses = MemberJpaRepository.class)
@EnableMongoRepositories(basePackageClasses = MemberMongoRepository.class)
@EnableDiscoveryClient
@SpringBootApplication
public class MemberApplication {

View File

@@ -0,0 +1,29 @@
package kiz.app.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
@Configuration
// @RequiredArgsConstructor
public class MongoDBConfig {
// private final MongoMappingContext mongoMappingContext;
@Bean
public MappingMongoConverter mappingMongoConverter(
MongoDatabaseFactory mongoDatabaseFactory,
MongoMappingContext mongoMappingContext
) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
}

View File

@@ -0,0 +1,24 @@
package kiz.app.common.event;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.stereotype.Component;
import kiz.app.common.service.MongoDbSeqGeneratorService;
import kiz.app.member.adapter.out.persistence.entity.MemberQueryEntity;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Component
public class MongoDbEventListener extends AbstractMongoEventListener<Object> {
private final MongoDbSeqGeneratorService generatorService;
@Override
public void onBeforeConvert(BeforeConvertEvent<Object> event) {
Object source = event.getSource();
if ((source instanceof MemberQueryEntity)) {
((MemberQueryEntity) source).setId(generatorService.generateSequence(MemberQueryEntity.SEQUENCE_NAME));
}
}
}

View File

@@ -0,0 +1,28 @@
package kiz.app.common.service;
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import java.util.Objects;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import kiz.app.member.adapter.out.persistence.entity.sequence.MongoDbSequence;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Service
public class MongoDbSeqGeneratorService {
private final MongoOperations mongoOperations;
public Long generateSequence(String seqName) {
MongoDbSequence counter = mongoOperations.findAndModify(Query.query(where("_id").is(seqName)),
new Update().inc("seq", 1), options().returnNew(true).upsert(true), MongoDbSequence.class);
return !Objects.isNull(counter) ? counter.getSeq() : 1;
}
}

View File

@@ -10,7 +10,7 @@ import kiz.app.common.WebAdapter;
import kiz.app.member.adapter.in.web.dto.MemberListResponse;
import kiz.app.member.adapter.in.web.dto.MemberResponse;
import kiz.app.member.adapter.in.web.mapper.MemberWebMapper;
import kiz.app.member.application.port.in.FindMemberUseCase;
import kiz.app.member.application.port.in.FindMemberQuery;
import lombok.RequiredArgsConstructor;
@WebAdapter
@@ -18,7 +18,7 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class FindMemberController {
private final FindMemberUseCase findMemberUseCase;
private final FindMemberQuery findMemberUseCase;
private final MemberWebMapper memberWebMapper;
@GetMapping("/members")

View File

@@ -7,20 +7,21 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import kiz.app.common.WebAdapter;
import kiz.app.member.adapter.in.web.dto.SignUpRequest;
import kiz.app.member.application.port.in.SignUpUseCase;
import kiz.app.member.application.port.in.command.SignUpCommand;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@WebAdapter
@RestController
@RequiredArgsConstructor
public class SignUpController {
private final SignUpUseCase signUpUseCase;
@PostMapping("/signup")
public Long signUp(@Valid @RequestBody SignUpCommand command) {
return signUpUseCase.signUp(command).getValue();
public Long signUp(@Valid @RequestBody final SignUpRequest request) {
return signUpUseCase.signUp(request.toCommand()).getValue();
}
}

View File

@@ -0,0 +1,28 @@
package kiz.app.member.adapter.in.web.dto;
import java.time.LocalDate;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import kiz.app.member.application.port.in.command.SignUpCommand;
public record SignUpRequest(
@NotEmpty
String memberId,
@NotEmpty
String password,
@NotEmpty
String memberName,
@Email
String email,
String phone,
String zipCode,
String address1,
String address2,
LocalDate birthday
) {
public SignUpCommand toCommand() {
return new SignUpCommand(memberId, password, memberName, email, phone, zipCode, address1, address2, birthday);
}
}

View File

@@ -1,7 +1,6 @@
package kiz.app.member.adapter.in.web.mapper;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Component;
@@ -34,7 +33,7 @@ public class MemberWebMapper {
item.getPhone().getValue(),
item.getAddress().getZipCode() + item.getAddress().getAddress1() + item.getAddress().getAddress2(),
item.getBirthday());
}).collect(Collectors.toList());
}).toList();
}
}

View File

@@ -8,17 +8,20 @@ import javax.persistence.EntityNotFoundException;
import kiz.app.common.PersistenceAdapter;
import kiz.app.member.adapter.out.persistence.mapper.MemberMapper;
import kiz.app.member.adapter.out.persistence.repository.MemberJpaRepository;
import kiz.app.member.adapter.out.persistence.repository.MemberMongoRepository;
import kiz.app.member.application.port.out.FindMemberPort;
import kiz.app.member.application.port.out.SignUpPort;
import kiz.app.member.domain.Member;
import kiz.app.member.domain.Member.MemberId;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@PersistenceAdapter
public class MemberPersistenceAdapter implements FindMemberPort, SignUpPort {
private final MemberJpaRepository memberJpaRepository;
private final MemberMongoRepository memberMongoRepository;
private final MemberMapper memberMapper;
@Override
@@ -29,14 +32,14 @@ public class MemberPersistenceAdapter implements FindMemberPort, SignUpPort {
@Override
public Member findByMemberId(String memberId) {
return memberMapper.toDomain(
memberJpaRepository.findByMemberId(memberId)
memberMongoRepository.findByMemberId(memberId)
.orElseThrow(EntityNotFoundException::new)
);
}
@Override
public List<Member> findAll() {
return memberJpaRepository.findAll()
return memberMongoRepository.findAll()
.stream()
.map(memberMapper::toDomain)
.collect(Collectors.toList());

View File

@@ -1,4 +1,4 @@
package kiz.app.member.adapter.out.persistence;
package kiz.app.member.adapter.out.persistence.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;

View File

@@ -0,0 +1,71 @@
package kiz.app.member.adapter.out.persistence.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.data.mongodb.core.mapping.FieldType;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Document(collection = "memberQuery")
public class MemberQueryEntity {
@Transient
public static final String SEQUENCE_NAME = "member_sequence";
@Id @Setter
private Long id;
@Indexed(unique = true)
@Field(name = "memberId", targetType = FieldType.STRING)
private String memberId;
@Field(name = "password", targetType = FieldType.STRING)
private String password;
@Field(name = "memberName", targetType = FieldType.STRING)
private String memberName;
@Indexed(unique = true)
@Field(name = "email", targetType = FieldType.STRING)
private String email;
@Field(name = "phone", targetType = FieldType.STRING)
private String phone;
@Field(name = "zipCode", targetType = FieldType.STRING)
private String zipCode;
@Field(name = "address1", targetType = FieldType.STRING)
private String address1;
@Field(name = "address2", targetType = FieldType.STRING)
private String address2;
@Field(name = "birthday", targetType = FieldType.STRING)
private LocalDate birthday;
@Field(name = "regId", targetType = FieldType.STRING)
private String regId;
@Field(name = "regDate", targetType = FieldType.TIMESTAMP)
private LocalDateTime regDate;
@Field(name = "modId", targetType = FieldType.STRING)
private String modId;
@Field(name = "modDate", targetType = FieldType.TIMESTAMP)
private LocalDateTime modDate;
}

View File

@@ -0,0 +1,19 @@
package kiz.app.member.adapter.out.persistence.entity.sequence;
import javax.persistence.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Document(collection = "mongodb_sequence")
public class MongoDbSequence {
@Id
private String id;
private Long seq;
}

View File

@@ -2,7 +2,8 @@ package kiz.app.member.adapter.out.persistence.mapper;
import org.springframework.stereotype.Component;
import kiz.app.member.adapter.out.persistence.MemberEntity;
import kiz.app.member.adapter.out.persistence.entity.MemberEntity;
import kiz.app.member.adapter.out.persistence.entity.MemberQueryEntity;
import kiz.app.member.domain.Address;
import kiz.app.member.domain.Email;
import kiz.app.member.domain.Member;
@@ -11,7 +12,7 @@ import kiz.app.member.domain.Phone;
@Component
public class MemberMapper {
public Member toDomain(MemberEntity member) {
public Member toDomain(MemberQueryEntity member) {
return Member.builder()
.memberId(member.getMemberId())
.password(member.getPassword())

View File

@@ -1,13 +1,9 @@
package kiz.app.member.adapter.out.persistence.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import kiz.app.member.adapter.out.persistence.MemberEntity;
import kiz.app.member.adapter.out.persistence.entity.MemberEntity;
public interface MemberJpaRepository extends JpaRepository<MemberEntity, Long> {
Optional<MemberEntity> findByMemberId(String memberId);
}

View File

@@ -0,0 +1,13 @@
package kiz.app.member.adapter.out.persistence.repository;
import java.util.Optional;
import org.springframework.data.mongodb.repository.MongoRepository;
import kiz.app.member.adapter.out.persistence.entity.MemberQueryEntity;
public interface MemberMongoRepository extends MongoRepository<MemberQueryEntity, Long> {
Optional<MemberQueryEntity> findByMemberId(String memberId);
}

View File

@@ -4,7 +4,7 @@ import java.util.List;
import kiz.app.member.domain.Member;
public interface FindMemberUseCase {
public interface FindMemberQuery {
Member getMember(String memberId);

View File

@@ -1,5 +0,0 @@
package kiz.app.member.application.port.in;
public interface LoginUseCase {
}

View File

@@ -1,24 +0,0 @@
package kiz.app.member.application.port.in.command;
import javax.validation.constraints.NotNull;
import kiz.app.common.SelfValidating;
import lombok.EqualsAndHashCode;
import lombok.Value;
@Value
@EqualsAndHashCode(callSuper = false)
public class LoginCommand extends SelfValidating<LoginCommand> {
@NotNull
private final String memberId;
@NotNull
private final String password;
public LoginCommand(String memberId, String password) {
this.memberId = memberId;
this.password = password;
this.validateSelf();
}
}

View File

@@ -2,17 +2,10 @@ package kiz.app.member.application.port.in.command;
import java.time.LocalDate;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
public record SignUpCommand (
@NotEmpty
String memberId,
@NotEmpty
String password,
@NotEmpty
String memberName,
@Email
String email,
String phone,
String zipCode,

View File

@@ -3,14 +3,14 @@ package kiz.app.member.application.service;
import java.util.List;
import kiz.app.common.UseCase;
import kiz.app.member.application.port.in.FindMemberUseCase;
import kiz.app.member.application.port.in.FindMemberQuery;
import kiz.app.member.application.port.out.FindMemberPort;
import kiz.app.member.domain.Member;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@UseCase
public class FindMemberService implements FindMemberUseCase {
public class FindMemberService implements FindMemberQuery {
private final FindMemberPort findMemberPort;

View File

@@ -1,5 +0,0 @@
package kiz.app.member.application.service;
public class LoginService {
}

View File

@@ -8,9 +8,10 @@ import kiz.app.member.application.port.in.command.SignUpCommand;
import kiz.app.member.application.port.out.SignUpPort;
import kiz.app.member.domain.Member;
import kiz.app.member.domain.Member.MemberId;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@UseCase
public class SignUpService implements SignUpUseCase {
@@ -18,7 +19,7 @@ public class SignUpService implements SignUpUseCase {
private final PasswordEncoder passwordEncoder;
@Override
public MemberId signUp(SignUpCommand command) {
public MemberId signUp(final SignUpCommand command) {
return signUpPort.signUp(
Member.createMember(
command.memberId(),

View File

@@ -7,6 +7,18 @@ spring:
config:
activate:
on-profile: local
cloud:
function:
definition: producer
stream:
kafka:
bindings:
producer-out-0:
producer:
# configuration:
# value.serializer: com.amrut.prabhu.dto.coverters.MessageSerializer
binder:
brokers: mindol.synology.me:19092
h2:
console:
enabled: true
@@ -32,7 +44,11 @@ spring:
ddl-auto: update
properties: # property 사용 설정
hibernate: # hibernate property 설정
format_sql: true
ogm:
datastore:
create:
database: true
format-sql: true
management:
endpoints:
@@ -45,6 +61,9 @@ management:
logging:
level:
kiz.app: DEBUG
org.hibernate.SQL: debug
org.hibernate.type: trace # 실제 들어가는 파라미터값 찍어주는 설정
kiz:
app: DEBUG
org:
hibernate:
SQL: debug
type: trace

View File

@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.7'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}

37
product-service/.gitignore vendored Normal file
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,51 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.8'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'com.kiz'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', "2021.0.5")
}
dependencies {
implementation project(':core-service')
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-aop'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
implementation 'org.springframework.cloud:spring-cloud-starter-stream-kafka'
implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j'
implementation 'org.springframework.cloud:spring-cloud-starter-sleuth:3.1.6'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
tasks.named('test') {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
product-service/gradlew vendored Normal file
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" "$@"

91
product-service/gradlew.bat vendored Normal file
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,4 @@
rootProject.name = 'product-service'
include ':core-service'
project(':core-service').projectDir = new File(settingsDir, '../core-service')

View File

@@ -0,0 +1,18 @@
package com.kiz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.kiz.adapter.out.persistence.jpa.StoreJpaRepository;
// @EnableJpaRepositories(basePackages = "com.kiz.adapter.out.persistence.jpa")
@EnableJpaRepositories(basePackageClasses = StoreJpaRepository.class)
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}

View File

@@ -0,0 +1,36 @@
package com.kiz.adapter.in.web.api;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.kiz.adapter.in.web.dto.StoreCreateRequest;
import com.kiz.application.command.CreateStoreCommand;
import com.kiz.application.port.in.CreateStoreUseCase;
import com.kiz.common.WebAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@WebAdapter
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/store")
public class StoreCreateController {
private final CreateStoreUseCase createStoreUseCase;
@PostMapping
public ResponseEntity<String> save(@Valid @RequestBody final StoreCreateRequest request) {
final var id = createStoreUseCase.handle(new CreateStoreCommand(request.storeName(), request.storeLocation(), request.storeDescription()));
log.info("Created store id: {}", id);
return ResponseEntity.status(HttpStatus.CREATED).body(id);
}
}

View File

@@ -0,0 +1,12 @@
package com.kiz.adapter.in.web.dto;
import javax.validation.constraints.NotEmpty;
public record StoreCreateRequest(
@NotEmpty
String storeName,
String storeLocation,
String storeDescription
) {
}

View File

@@ -0,0 +1,34 @@
package com.kiz.adapter.out.message;
import java.util.List;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.stereotype.Service;
import com.kiz.event.Event;
import com.kiz.event.EventBus;
import com.kiz.event.SerializerUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class KafkaEventBus implements EventBus {
private final StreamBridge streamBridge;
@Override
public void publish(List<Event> events) {
final byte[] eventsBytes = SerializerUtils.serializeToJsonBytes(events.toArray(new Event[]{}));
try {
streamBridge.send("createStore-out-0", eventsBytes);
} catch (Exception ex) {
log.error("(KafkaEventBus) publish get timeout", ex);
throw new RuntimeException(ex);
}
}
}

View File

@@ -0,0 +1,54 @@
package com.kiz.adapter.out.persistence;
import org.springframework.cloud.sleuth.annotation.NewSpan;
import com.kiz.application.port.out.LoadStorePort;
import com.kiz.application.port.out.SaveStorePort;
import com.kiz.application.port.out.UpdateStorePort;
import com.kiz.common.PersistenceAdapter;
import com.kiz.domain.model.Store;
import com.kiz.event.EventStoreDB;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@PersistenceAdapter
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class StoreCommandAdapter implements SaveStorePort, UpdateStorePort, LoadStorePort {
private final EventStoreDB eventStoreDB;
private static final String SERVICE_NAME = "microservice";
@Override
@NewSpan
@Retry(name = SERVICE_NAME)
@CircuitBreaker(name = SERVICE_NAME)
public Store load(String aggregateId) {
return eventStoreDB.load(aggregateId, Store.class);
}
@Override
@NewSpan
@Retry(name = SERVICE_NAME)
@CircuitBreaker(name = SERVICE_NAME)
public String save(Store aggregate) {
eventStoreDB.save(aggregate);
log.info("(createStore) aggregate: {}", aggregate);
return aggregate.getId();
}
@Override
@NewSpan
@Retry(name = SERVICE_NAME)
@CircuitBreaker(name = SERVICE_NAME)
public Store updateStore(Store aggregate) {
eventStoreDB.save(aggregate);
log.info("(updateStore) aggregate: {}", aggregate);
return aggregate;
}
}

View File

@@ -0,0 +1,27 @@
package com.kiz.adapter.out.persistence;
import com.kiz.adapter.out.persistence.jpa.StoreJpaRepository;
import com.kiz.application.port.out.GetStoreByIdPort;
import com.kiz.application.query.GetStoreByIdQuery;
import com.kiz.common.PersistenceAdapter;
import com.kiz.domain.model.Store;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@PersistenceAdapter
@Slf4j
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class StoreQueryAdapter implements GetStoreByIdPort {
private final StoreJpaRepository storeJpaRepository;
@Override
public Store getStoreById(GetStoreByIdQuery query) {
log.info("(GetStoreByIdQuery) query: {}", query);
storeJpaRepository.findByStoreId(query.id());
return null;
}
}

View File

@@ -0,0 +1,211 @@
package com.kiz.adapter.out.persistence.jdbc;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.springframework.cloud.sleuth.annotation.NewSpan;
import org.springframework.cloud.sleuth.annotation.SpanTag;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.kiz.event.AggregateRoot;
import com.kiz.event.Event;
import com.kiz.event.EventBus;
import com.kiz.event.EventSourcingUtils;
import com.kiz.event.EventStoreDB;
import com.kiz.event.Snapshot;
import com.kiz.event.exceptions.AggregateNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import static com.kiz.event.Constants.*;
// @Repository
@RequiredArgsConstructor
@Slf4j
public class JdbcEventStore implements EventStoreDB {
public static final int SNAPSHOT_FREQUENCY = 3;
private static final String SAVE_EVENTS_QUERY = "INSERT INTO events (aggregate_id, aggregate_type, event_type, data, metadata, version, timestamp) values (:aggregate_id, :aggregate_type, :event_type, :data, :metadata, :version, now())";
private static final String LOAD_EVENTS_QUERY = "SELECT event_id ,aggregate_id, aggregate_type, event_type, data, metadata, version, timestamp FROM events e WHERE e.aggregate_id = :aggregate_id AND e.version > :version ORDER BY e.version ASC";
private static final String SAVE_SNAPSHOT_QUERY = "INSERT INTO snapshots (aggregate_id, aggregate_type, data, metadata, version, timestamp) VALUES (:aggregate_id, :aggregate_type, :data, :metadata, :version, now()) ON CONFLICT (aggregate_id) DO UPDATE SET data = :data, version = :version, timestamp = now()";
private static final String HANDLE_CONCURRENCY_QUERY = "SELECT aggregate_id FROM events e WHERE e.aggregate_id = :aggregate_id LIMIT 1 FOR UPDATE";
private static final String LOAD_SNAPSHOT_QUERY = "SELECT aggregate_id, aggregate_type, data, metadata, version, timestamp FROM snapshots s WHERE s.aggregate_id = :aggregate_id";
private static final String EXISTS_QUERY = "SELECT aggregate_id FROM events WHERE e e.aggregate_id = :aggregate_id";
// private final NamedParameterJdbcTemplate jdbcTemplate;
private final EventBus eventBus;
@Override
@Transactional
@NewSpan
public <T extends AggregateRoot> void save(@SpanTag("aggregate") T aggregate) {
final List<Event> aggregateEvents = new ArrayList<>(aggregate.getChanges());
if (aggregate.getVersion() > 1) {
this.handleConcurrency(aggregate.getId());
}
this.saveEvents(aggregate.getChanges());
if (aggregate.getVersion() % SNAPSHOT_FREQUENCY == 0) {
this.saveSnapshot(aggregate);
}
eventBus.publish(aggregateEvents);
log.info("(save) saved aggregate: {}", aggregate);
}
@Override
@Transactional(readOnly = true)
@NewSpan
public <T extends AggregateRoot> T load(@SpanTag("aggregateId") String aggregateId, @SpanTag("aggregateType") Class<T> aggregateType) {
final Optional<Snapshot> snapshot = this.loadSnapshot(aggregateId);
final var aggregate = this.getSnapshotFromClass(snapshot, aggregateId, aggregateType);
final List<Event> events = this.loadEvents(aggregateId, aggregate.getVersion());
events.forEach(event -> {
aggregate.raiseEvent(event);
log.info("raise event version: {}", event.getVersion());
});
if (aggregate.getVersion() == 0) throw new AggregateNotFoundException(aggregateId);
log.info("(load) loaded aggregate: {}", aggregate);
return aggregate;
}
@Override
@NewSpan
public void saveEvents(@SpanTag("events") List<Event> events) {
if (events.isEmpty()) return;
final List<Event> changes = new ArrayList<>(events);
if (changes.size() > 1) {
this.eventsBatchInsert(changes);
return;
}
final Event event = changes.get(0);
// int result = jdbcTemplate.update(SAVE_EVENTS_QUERY, mapFromEvent(event));
// log.info("(saveEvents) saved result: {}, event: {}", result, event);
}
private Map<String, Serializable> mapFromEvent(Event event) {
return Map.of(
AGGREGATE_ID, event.getAggregateId(),
AGGREGATE_TYPE, event.getAggregateType(),
EVENT_TYPE, event.getEventType(),
DATA, Objects.isNull(event.getData()) ? new byte[]{} : event.getData(),
METADATA, Objects.isNull(event.getMetaData()) ? new byte[]{} : event.getMetaData(),
VERSION, event.getVersion());
}
@NewSpan
@SuppressWarnings("unchecked")
private void eventsBatchInsert(@SpanTag("events") List<Event> events) {
final var args = events.stream().map(this::mapFromEvent).toList();
final Map<String, ?>[] maps = args.toArray(new Map[0]);
// int[] ints = jdbcTemplate.batchUpdate(SAVE_EVENTS_QUERY, maps);
// log.info("(saveEvents) BATCH saved result: {}, event: {}", ints);
}
@Override
@NewSpan
public List<Event> loadEvents(@SpanTag("aggregateId") String aggregateId, @SpanTag("version") long version) {
// return jdbcTemplate.query(LOAD_EVENTS_QUERY, Map.of(AGGREGATE_ID, aggregateId, VERSION, version),
// (rs, rowNum) -> Event.builder()
// .aggregateId(rs.getString(AGGREGATE_ID))
// .aggregateType(rs.getString(AGGREGATE_TYPE))
// .eventType(rs.getString(EVENT_TYPE))
// .data(rs.getBytes(DATA))
// .metaData(rs.getBytes(METADATA))
// .version(rs.getLong(VERSION))
// .timeStamp(rs.getTimestamp(TIMESTAMP).toLocalDateTime())
// .build());
return null;
}
@NewSpan
private <T extends AggregateRoot> void saveSnapshot(@SpanTag("aggregate") T aggregate) {
aggregate.toSnapshot();
final var snapshot = EventSourcingUtils.snapshotFromAggregate(aggregate);
// int updateResult = jdbcTemplate.update(SAVE_SNAPSHOT_QUERY,
// Map.of(AGGREGATE_ID, snapshot.getAggregateId(),
// AGGREGATE_TYPE, snapshot.getAggregateType(),
// DATA, Objects.isNull(snapshot.getData()) ? new byte[]{} : snapshot.getData(),
// METADATA, Objects.isNull(snapshot.getMetaData()) ? new byte[]{} : snapshot.getMetaData(),
// VERSION, snapshot.getVersion()));
// log.info("(saveSnapshot) updateResult: {}", updateResult);
}
@NewSpan
private void handleConcurrency(@SpanTag("aggregateId") String aggregateId) {
try {
// String aggregateID = jdbcTemplate.queryForObject(HANDLE_CONCURRENCY_QUERY, Map.of(AGGREGATE_ID, aggregateId), String.class);
// log.info("(handleConcurrency) aggregateID for lock: {}", aggregateID);
} catch (EmptyResultDataAccessException e) {
log.info("(handleConcurrency) EmptyResultDataAccessException: {}", e.getMessage());
}
log.info("(handleConcurrency) aggregateID for lock: {}", aggregateId);
}
@NewSpan
private Optional<Snapshot> loadSnapshot(@SpanTag("aggregateId") String aggregateId) {
// return jdbcTemplate.query(LOAD_SNAPSHOT_QUERY, Map.of(AGGREGATE_ID, aggregateId), (rs, rowNum) -> Snapshot.builder()
// .aggregateId(rs.getString(AGGREGATE_ID))
// .aggregateType(rs.getString(AGGREGATE_TYPE))
// .data(rs.getBytes(DATA))
// .metaData(rs.getBytes(METADATA))
// .version(rs.getLong(VERSION))
// .timeStamp(rs.getTimestamp(TIMESTAMP).toLocalDateTime())
// .build()).stream().findFirst();
return null;
}
@NewSpan
private <T extends AggregateRoot> T getAggregate(@SpanTag("aggregateId") final String aggregateId, @SpanTag("aggregateType") final Class<T> aggregateType) {
try {
return aggregateType.getConstructor(String.class).newInstance(aggregateId);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@NewSpan
private <T extends AggregateRoot> T getSnapshotFromClass(@SpanTag("snapshot") Optional<Snapshot> snapshot, @SpanTag("aggregateId") String aggregateId, @SpanTag("aggregateType") Class<T> aggregateType) {
if (snapshot.isEmpty()) {
final var defaultSnapshot = EventSourcingUtils.snapshotFromAggregate(getAggregate(aggregateId, aggregateType));
return EventSourcingUtils.aggregateFromSnapshot(defaultSnapshot, aggregateType);
}
return EventSourcingUtils.aggregateFromSnapshot(snapshot.get(), aggregateType);
}
@Override
@NewSpan
public Boolean exists(@SpanTag("aggregateId") String aggregateId) {
try {
// final var id = jdbcTemplate.queryForObject(EXISTS_QUERY, Map.of(AGGREGATE_ID, aggregateId), String.class);
// log.info("aggregate exists id: {}", id);
return true;
} catch (Exception ex) {
if (!(ex instanceof EmptyResultDataAccessException)) {
throw new RuntimeException(ex);
}
return false;
}
}
}

View File

@@ -0,0 +1,41 @@
package com.kiz.adapter.out.persistence.jpa;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name = "store")
public class StoreEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "store_id")
@Getter private Long storeId;
@Column(name = "aggregate_id", length = 36, nullable = false, unique = true)
@Getter private String aggregateId;
@Column(name = "store_name", length = 50, nullable = false)
@Getter private String storeName;
@Column(name = "store_location", length = 50, nullable = false)
@Getter private String storeLocation;
@Column(name = "store_description", length = 1000)
@Getter private String storeDescription;
@Builder
public StoreEntity(String aggregateId, String storeName, String storeLocation, String storeDescription) {
this.aggregateId = aggregateId;
this.storeName = storeName;
this.storeLocation = storeLocation;
this.storeDescription = storeDescription;
}
}

View File

@@ -0,0 +1,15 @@
package com.kiz.adapter.out.persistence.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StoreJpaRepository extends JpaRepository<StoreEntity, Long> {
Optional<StoreEntity> findByStoreId(Long storeId);
Optional<StoreEntity> findByAggregateId(String aggregateId);
void deleteByAggregateId(String aggregateId);
}

View File

@@ -0,0 +1,99 @@
package com.kiz.adapter.out.persistence.projection;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import org.springframework.cloud.sleuth.annotation.NewSpan;
import org.springframework.cloud.sleuth.annotation.SpanTag;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.kiz.adapter.out.persistence.jpa.StoreEntity;
import com.kiz.adapter.out.persistence.jpa.StoreJpaRepository;
import com.kiz.domain.event.StoreCreateEvent;
import com.kiz.domain.model.Store;
import com.kiz.event.Event;
import com.kiz.event.EventStoreDB;
import com.kiz.event.Projection;
import com.kiz.event.SerializerUtils;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.retry.annotation.Retry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
@Service
public class StoreJpaProjection implements Projection {
private final StoreJpaRepository storeJpaRepository;
private final EventStoreDB eventStoreDB;
private static final String SERVICE_NAME = "microservice";
@Bean
private Consumer<byte[]> createStore() {
return (data) -> {
log.info("createStore 이벤트 수신");
try {
final Event[] events = SerializerUtils.deserializeEventsFromJsonBytes(data);
this.processEvents(Arrays.stream(events).toList());
} catch (Exception ex) {
log.error("(CreateStoreProjection)", ex);
}
};
}
@NewSpan
private void processEvents(@SpanTag("events") List<Event> events) {
if (events.isEmpty()) return;
try {
events.forEach(this::when);
} catch (Exception ex) {
storeJpaRepository.deleteByAggregateId(events.get(0).getAggregateId());
final var aggregate = eventStoreDB.load(events.get(0).getAggregateId(), Store.class);
final var result = storeJpaRepository.save(
StoreEntity.builder()
.aggregateId(aggregate.getId())
.storeName(aggregate.getStoreName())
.storeLocation(aggregate.getStoreLocation())
.storeDescription(aggregate.getStoreDescription())
.build()
);
log.info("(processEvents) saved entity: {}", result);
}
}
@NewSpan
@Retry(name = SERVICE_NAME)
@CircuitBreaker(name = SERVICE_NAME)
@Override
public void when(@SpanTag("event") Event event) {
final var aggregateId = event.getAggregateId();
log.info("(when) >>>>> aggregateId: {}", aggregateId);
switch (event.getEventType()) {
case StoreCreateEvent.STORE_CREATED_V1 ->
handle(SerializerUtils.deserializeFromJsonBytes(event.getData(), StoreCreateEvent.class));
default -> log.error("unknown event type: {}", event.getEventType());
}
}
@NewSpan
private void handle(@SpanTag("event") StoreCreateEvent event) {
log.info("(when) StoreCreateEvent: {}, aggregateID: {}", event, event.getAggregateId());
final var entity = StoreEntity.builder()
.aggregateId(event.getAggregateId())
.storeName(event.getStoreName())
.storeLocation(event.getStoreLocation())
.storeDescription(event.getStoreDescription())
.build();
final var insert = storeJpaRepository.save(entity);
log.info("(StoreCreateEvent) insert: {}", insert);
}
}

View File

@@ -0,0 +1,5 @@
package com.kiz.application.command;
public record CreateStoreCommand(String storeName, String storeLocation, String storeDescription) {
}

View File

@@ -0,0 +1,5 @@
package com.kiz.application.command;
public record UpdateStoreCommand(String aggregateId, String storeName, String storeLocation, String storeDescription) {
}

View File

@@ -0,0 +1,7 @@
package com.kiz.application.port.in;
import com.kiz.application.command.CreateStoreCommand;
public interface CreateStoreUseCase {
String handle(CreateStoreCommand command);
}

View File

@@ -0,0 +1,5 @@
package com.kiz.application.port.in;
public interface FindAllStoreUseCase {
}

View File

@@ -0,0 +1,5 @@
package com.kiz.application.port.in;
public interface FindSearchStoreUseCase {
}

View File

@@ -0,0 +1,8 @@
package com.kiz.application.port.in;
import com.kiz.application.query.GetStoreByIdQuery;
import com.kiz.domain.model.Store;
public interface GetStoreByIdUseCase {
Store handle(GetStoreByIdQuery query);
}

View File

@@ -0,0 +1,8 @@
package com.kiz.application.port.in;
import com.kiz.application.command.UpdateStoreCommand;
import com.kiz.domain.model.Store;
public interface UpdateStoreUseCase {
Store handle(UpdateStoreCommand command);
}

View File

@@ -0,0 +1,8 @@
package com.kiz.application.port.out;
import com.kiz.application.query.GetStoreByIdQuery;
import com.kiz.domain.model.Store;
public interface GetStoreByIdPort {
Store getStoreById(GetStoreByIdQuery query);
}

View File

@@ -0,0 +1,7 @@
package com.kiz.application.port.out;
import com.kiz.domain.model.Store;
public interface LoadStorePort {
Store load(String aggregateId);
}

View File

@@ -0,0 +1,7 @@
package com.kiz.application.port.out;
import com.kiz.domain.model.Store;
public interface SaveStorePort {
String save(Store aggregate);
}

View File

@@ -0,0 +1,7 @@
package com.kiz.application.port.out;
import com.kiz.domain.model.Store;
public interface UpdateStorePort {
Store updateStore(Store aggregate);
}

View File

@@ -0,0 +1,5 @@
package com.kiz.application.query;
public record GetStoreByIdQuery(Long id) {
}

View File

@@ -0,0 +1,25 @@
package com.kiz.application.service;
import com.kiz.application.command.CreateStoreCommand;
import com.kiz.application.port.in.CreateStoreUseCase;
import com.kiz.application.port.out.SaveStorePort;
import com.kiz.common.UseCase;
import com.kiz.domain.model.Store;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@UseCase
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class CreateStoreService implements CreateStoreUseCase {
private final SaveStorePort saveStorePort;
@Override
public String handle(CreateStoreCommand command) {
final var aggregate = new Store(new Store.StoreId().getValue());
aggregate.createStore(command.storeName() , command.storeLocation(), command.storeDescription());
return saveStorePort.save(aggregate);
}
}

View File

@@ -0,0 +1,20 @@
package com.kiz.application.service;
import com.kiz.application.port.in.GetStoreByIdUseCase;
import com.kiz.application.query.GetStoreByIdQuery;
import com.kiz.common.UseCase;
import com.kiz.domain.model.Store;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@UseCase
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class GetStoreByIdService implements GetStoreByIdUseCase {
@Override
public Store handle(GetStoreByIdQuery query) {
return null;
}
}

View File

@@ -0,0 +1,27 @@
package com.kiz.application.service;
import com.kiz.application.command.UpdateStoreCommand;
import com.kiz.application.port.in.UpdateStoreUseCase;
import com.kiz.application.port.out.LoadStorePort;
import com.kiz.application.port.out.UpdateStorePort;
import com.kiz.common.UseCase;
import com.kiz.domain.model.Store;
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@UseCase
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class UpdateStoreService implements UpdateStoreUseCase {
private final LoadStorePort storeLoadPort;
private final UpdateStorePort storeUpdatePort;
@Override
public Store handle(UpdateStoreCommand command) {
final var aggregate = storeLoadPort.load(command.aggregateId());
aggregate.updateStore(command.storeName(), command.storeLocation(), command.storeDescription());
return storeUpdatePort.updateStore(aggregate);
}
}

View File

@@ -0,0 +1,21 @@
package com.kiz.common.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
@Configuration
public class JdbcConfig {
@Autowired
private DataSource dataSource;
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
return new NamedParameterJdbcTemplate(dataSource);
}
}

View File

@@ -0,0 +1,30 @@
package com.kiz.domain.event;
import com.kiz.domain.model.Store;
import com.kiz.event.BaseEvent;
import lombok.Builder;
import lombok.Getter;
public class CategoryCreateEvent extends BaseEvent {
public static final String CATEGORY_CREATED_V1 = "CATEGORY_CREATED_V1";
public static final String AGGREGATE_TYPE = Store.AGGREGATE_TYPE;
@Getter private String storeId;
@Getter private int categoryLevel;
@Getter private Long categoryParentId;
@Getter private String categoryName;
@Getter private String categoryDescription;
@Builder
public CategoryCreateEvent(String aggregateId, String storeId, int categoryLevel, Long categoryParentId, String categoryName, String categoryDescription) {
super(aggregateId);
this.storeId = storeId;
this.categoryLevel = categoryLevel;
this.categoryParentId = categoryParentId;
this.categoryName = categoryName;
this.categoryDescription = categoryDescription;
}
}

View File

@@ -0,0 +1,26 @@
package com.kiz.domain.event;
import com.kiz.domain.model.Store;
import com.kiz.event.BaseEvent;
import lombok.Builder;
import lombok.Getter;
public class StoreCreateEvent extends BaseEvent {
public static final String STORE_CREATED_V1 = "STORE_CREATED_V1";
public static final String AGGREGATE_TYPE = Store.AGGREGATE_TYPE;
@Getter private String storeName;
@Getter private String storeLocation;
@Getter private String storeDescription;
@Builder
public StoreCreateEvent(String aggregateId, String storeName, String storeLocation, String storeDescription) {
super(aggregateId);
this.storeName = storeName;
this.storeLocation = storeLocation;
this.storeDescription = storeDescription;
}
}

View File

@@ -0,0 +1,26 @@
package com.kiz.domain.event;
import com.kiz.domain.model.Store;
import com.kiz.event.BaseEvent;
import lombok.Builder;
import lombok.Getter;
public class StoreUpdateEvent extends BaseEvent {
public static final String STORE_UPDATE_V1 = "STORE_UPDATE_V1";
public static final String AGGREGATE_TYPE = Store.AGGREGATE_TYPE;
@Getter private String storeName;
@Getter private String storeLocation;
@Getter private String storeDescription;
@Builder
public StoreUpdateEvent(String aggregateId, String storeName, String storeLocation, String storeDescription) {
super(aggregateId);
this.storeName = storeName;
this.storeLocation = storeLocation;
this.storeDescription = storeDescription;
}
}

View File

@@ -0,0 +1,12 @@
package com.kiz.domain.exception;
public class InvalidCategoryNameException extends RuntimeException {
public InvalidCategoryNameException() {
}
public InvalidCategoryNameException(String categoryName) {
super("invalid categoryName: " + categoryName);
}
}

View File

@@ -0,0 +1,22 @@
package com.kiz.domain.model;
import java.util.UUID;
import lombok.Getter;
public class Category {
public static class CategoryId {
@Getter private final String value;
public CategoryId() {
this.value = UUID.randomUUID().toString();
}
}
@Getter private int categoryLevel;
@Getter private Long categoryParentId;
@Getter private String categoryName;
@Getter private String categoryDescription;
@Getter private Store store;
}

View File

@@ -0,0 +1,5 @@
package com.kiz.domain.model;
public class Product {
}

View File

@@ -0,0 +1,5 @@
package com.kiz.domain.model;
public class ProductImage {
}

View File

@@ -0,0 +1,84 @@
package com.kiz.domain.model;
import java.util.UUID;
import com.kiz.domain.event.StoreCreateEvent;
import com.kiz.domain.event.StoreUpdateEvent;
import com.kiz.event.AggregateRoot;
import com.kiz.event.Event;
import com.kiz.event.SerializerUtils;
import com.kiz.event.exceptions.InvalidEventTypeException;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@EqualsAndHashCode(callSuper = false)
public class Store extends AggregateRoot {
public static final String AGGREGATE_TYPE = "StoreAggregate";
public Store(String id) {
super(id, AGGREGATE_TYPE);
}
public static class StoreId {
@Getter private final String value;
public StoreId() {
this.value = UUID.randomUUID().toString();
}
}
@Getter private String storeName;
@Getter private String storeLocation;
@Getter private String storeDescription;
@Override
public void when(Event event) {
switch (event.getEventType()) {
case StoreCreateEvent.STORE_CREATED_V1 ->
handle(SerializerUtils.deserializeFromJsonBytes(event.getData(), StoreCreateEvent.class));
case StoreUpdateEvent.STORE_UPDATE_V1 ->
handle(SerializerUtils.deserializeFromJsonBytes(event.getData(), StoreUpdateEvent.class));
default -> throw new InvalidEventTypeException(event.getEventType());
}
}
private void handle(final StoreCreateEvent event) {
this.storeName = event.getStoreName();
this.storeLocation = event.getStoreLocation();
this.storeDescription = event.getStoreDescription();
}
private void handle(final StoreUpdateEvent event) {
this.storeName = event.getStoreName();
this.storeLocation = event.getStoreLocation();
this.storeDescription = event.getStoreDescription();
}
public void createStore(String storeName, String storeLocation, String storeDescription) {
final var data = StoreCreateEvent.builder()
.aggregateId(id)
.storeName(storeName)
.storeLocation(storeLocation)
.storeDescription(storeDescription)
.build();
final byte[] dataBytes = SerializerUtils.serializeToJsonBytes(data);
final var event = this.createEvent(StoreCreateEvent.STORE_CREATED_V1, dataBytes, null);
this.apply(event);
}
public void updateStore(String storeName, String storeLocation, String storeDescription) {
final var data = StoreUpdateEvent.builder()
.aggregateId(id)
.storeName(storeName)
.storeLocation(storeLocation)
.storeDescription(storeDescription)
.build();
final byte[] dataBytes = SerializerUtils.serializeToJsonBytes(data);
final var event = this.createEvent(StoreUpdateEvent.STORE_UPDATE_V1, dataBytes, null);
this.apply(event);
}
}

View File

@@ -0,0 +1,12 @@
package com.kiz.domain.repository;
import java.util.List;
import com.kiz.domain.model.Store;
public interface StoreRepository {
Store save(Store order);
List<Store> findAll();
Store findById(Long id);
void delete(Store order);
}

View File

@@ -0,0 +1,55 @@
server:
port: 0
spring:
config:
activate:
on-profile: local
datasource:
driver-class-name: org.mariadb.jdbc.Driver
url: jdbc:mariadb://mindol.synology.me:3307/kiz_space
username: mindolangel
password: $awlswn1318A
jpa:
database: mysql
open-in-view: false
generate-ddl: true
show-sql: true
hibernate: # hibernate 사용 설정
ddl-auto: update
properties: # property 사용 설정
hibernate: # hibernate property 설정
ogm:
datastore:
create:
database: true
format-sql: true
cloud:
function:
definition: createStore
stream:
bindings:
createStore-out-0:
destination: store-create-topic
group: store-group
kafka:
binder:
brokers: mindol.synology.me:19092
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true
logging:
level:
com:
kiz: DEBUG
org:
hibernate:
SQL: debug
type: trace

View File

@@ -0,0 +1,27 @@
spring:
application:
name: product-service # 서비스 ID (컨피그 클라이언트가 어떤 서비스를 조회하는지 매핑)
profiles:
active: local # 서비스가 실행할 기본 프로파일
# cloud:
# config:
# uri: http://localhost:8889 # 컨피그 서버 위치
# name: user
# profile: default
eureka:
instance:
hostname: mindol.synology.me
instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}}
lease-renewal-interval-in-seconds: 30 # 유레카 서버로 설정된 시간(second)마다 하트비트 전송 (디폴트 30초)
# 디스커버리는 서비스 등록 해제 하기 전에 마지막 하트비트에서부터 설정된 시간(second) 동안 하트비트가 수신되지 않으면
# 서비스 등록 해제 (디폴트 90초)
lease-expiration-duration-in-seconds: 90
prefer-ip-address: true # 서비스의 호스트 이름이 아닌 IP 주소를 유레카 서버에 등록하도록 지정 (디폴트 false)
client:
register-with-eureka: true # 레지스트리에 자신을 등록할지에 대한 여부 (디폴트 true)
fetch-registry: true # 레지스트리에 있는 정보를 가져올지에 대한 여부 (디폴트 true)
registry-fetch-interval-seconds: 30 # 서비스 목록을 설정한 시간마다 캐싱 (디폴트 30초)
disable-delta: true # 캐싱 시 변경된 부분만 업데이트할 지 여부 (디폴트 false)
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:8761/eureka/

View File

@@ -0,0 +1,13 @@
package com.kiz;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProductServiceApplicationTests {
@Test
void contextLoads() {
}
}