This commit is contained in:
mindol1004
2023-03-16 17:45:18 +09:00
commit 9a57a83541
44 changed files with 1489 additions and 0 deletions

37
.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/

18
Dockerfile Normal file
View File

@@ -0,0 +1,18 @@
# 1. Gradle build
FROM openjdk:17-jdk AS builder
COPY gradlew .
COPY gradle gradle
COPY build.gradle .
COPY settings.gradle .
COPY src src
RUN chmod +x ./gradlew
RUN ./gradlew clean build -x test
# 2. 빌더로부터 jar 파일 메인 디렉토리에 복사 후 시스템 진입점 정의
FROM openjdk:17-jdk
ARG JAR_FILE=./build/libs/member-service-0.0.1-SNAPSHOT.jar
# JAR 파일 메인 디렉토리에 복사
COPY --from=builder ${JAR_FILE} app.jar
# 시스템 진입점 정의
EXPOSE 8083
ENTRYPOINT ["java","-jar","/app.jar"]

55
build.gradle Normal file
View File

@@ -0,0 +1,55 @@
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.9'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
}
group = 'kiz.space'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
ext {
set('springCloudVersion', "2021.0.5")
}
dependencies {
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-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'
runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
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()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

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.5.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
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
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

1
settings.gradle Normal file
View File

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

View File

@@ -0,0 +1,22 @@
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 {
public static void main(String[] args) {
SpringApplication.run(MemberApplication.class, args);
}
}

View File

@@ -0,0 +1,26 @@
package kiz.app.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,32 @@
package kiz.app.common;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.Validator;
public abstract class SelfValidating<T> {
private Validator validator;
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
public SelfValidating() {
validator = factory.getValidator();
}
/**
* Evaluates all Bean Validations on the attributes of this
* instance.
*/
@SuppressWarnings("unchecked")
protected void validateSelf() {
Set<ConstraintViolation<T>> violations = validator.validate((T) this);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
}

View File

@@ -0,0 +1,26 @@
package kiz.app.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 kiz.app.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,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,33 @@
package kiz.app.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors().disable() //cors 방지
.csrf().disable() //csrf 방지
.formLogin().disable() //기본 로그인페이지 없애기
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.and()
.headers().frameOptions().disable();
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}

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

@@ -0,0 +1,34 @@
package kiz.app.member.adapter.in.web;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
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.FindMemberQuery;
import lombok.RequiredArgsConstructor;
@WebAdapter
@RestController
@RequiredArgsConstructor
public class FindMemberController {
private final FindMemberQuery findMemberUseCase;
private final MemberWebMapper memberWebMapper;
@GetMapping("/members")
public List<MemberListResponse> getMembers() {
return memberWebMapper.toListDto(findMemberUseCase.getMembers());
}
@GetMapping("/members/{memberId}")
public MemberResponse getMember(@PathVariable("memberId") String memberId) {
return memberWebMapper.toDto(findMemberUseCase.getMember(memberId));
}
}

View File

@@ -0,0 +1,27 @@
package kiz.app.member.adapter.in.web;
import javax.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
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 lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
@WebAdapter
@RestController
public class SignUpController {
private final SignUpUseCase signUpUseCase;
@PostMapping("/signup")
public Long signUp(@Valid @RequestBody final SignUpRequest request) {
return signUpUseCase.signUp(request.toCommand()).getValue();
}
}

View File

@@ -0,0 +1,12 @@
package kiz.app.member.adapter.in.web.dto;
import java.time.LocalDate;
public record MemberListResponse(
String memberId,
String memberName,
String email,
String phone,
String address,
LocalDate birthday
) {}

View File

@@ -0,0 +1,29 @@
package kiz.app.member.adapter.in.web.dto;
import java.time.LocalDate;
import lombok.Builder;
import lombok.Getter;
@Getter
public class MemberResponse {
private String memberId;
private String password;
private String name;
private String email;
private String phone;
private String address;
private LocalDate birthday;
@Builder
public MemberResponse(String memberId, String password, String name, String email, String phone, String address,
LocalDate birthday) {
this.memberId = memberId;
this.password = password;
this.name = name;
this.email = email;
this.phone = phone;
this.address = address;
this.birthday = birthday;
}
}

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

@@ -0,0 +1,39 @@
package kiz.app.member.adapter.in.web.mapper;
import java.util.List;
import org.springframework.stereotype.Component;
import kiz.app.member.adapter.in.web.dto.MemberListResponse;
import kiz.app.member.adapter.in.web.dto.MemberResponse;
import kiz.app.member.domain.Member;
@Component
public class MemberWebMapper {
public MemberResponse toDto(Member member) {
return MemberResponse.builder()
.memberId(member.getMemberId())
.password(member.getPassword())
.name(member.getMemberName())
.email(member.getEmail().getValue())
.phone(member.getPhone().getValue())
.address(member.getAddress().getZipCode() + member.getAddress().getAddress1() + member.getAddress().getAddress2())
.birthday(member.getBirthday())
.build();
}
public List<MemberListResponse> toListDto(List<Member> member) {
return member.stream()
.map(item -> {
return new MemberListResponse(
item.getMemberId(),
item.getMemberName(),
item.getEmail().getValue(),
item.getPhone().getValue(),
item.getAddress().getZipCode() + item.getAddress().getAddress1() + item.getAddress().getAddress2(),
item.getBirthday());
}).toList();
}
}

View File

@@ -0,0 +1,48 @@
package kiz.app.member.adapter.out.persistence;
import java.util.List;
import java.util.stream.Collectors;
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(access = AccessLevel.PRIVATE)
@PersistenceAdapter
public class MemberPersistenceAdapter implements FindMemberPort, SignUpPort {
private final MemberJpaRepository memberJpaRepository;
private final MemberMongoRepository memberMongoRepository;
private final MemberMapper memberMapper;
@Override
public MemberId signUp(Member member) {
return new MemberId(memberJpaRepository.save(memberMapper.toEntity(member)).getId());
}
@Override
public Member findByMemberId(String memberId) {
return memberMapper.toDomain(
memberMongoRepository.findByMemberId(memberId)
.orElseThrow(EntityNotFoundException::new)
);
}
@Override
public List<Member> findAll() {
return memberMongoRepository.findAll()
.stream()
.map(memberMapper::toDomain)
.collect(Collectors.toList());
}
}

View File

@@ -0,0 +1,81 @@
package kiz.app.member.adapter.out.persistence.entity;
import java.time.LocalDate;
import java.time.LocalDateTime;
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)
@Getter
@Entity
@Table(name = "member")
public class MemberEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "member_id", length = 20, nullable = false, unique = true)
private String memberId;
@Column(name = "password", length = 1000, nullable = false)
private String password;
@Column(name = "memberName", length = 20, nullable = false)
private String memberName;
@Column(name = "email", length = 50, nullable = false)
private String email;
@Column(name = "phone", length = 20)
private String phone;
@Column(name = "zipCode", length = 6)
private String zipCode;
@Column(name = "address1", length = 100)
private String address1;
@Column(name = "address2", length = 100)
private String address2;
@Column(name = "birthday")
private LocalDate birthday;
@Column(name = "regId", length = 20)
private String regId;
@Column(name = "regDate")
private LocalDateTime regDate;
@Column(name = "modId", length = 20)
private String modId;
@Column(name = "modDate")
private LocalDateTime modDate;
@Builder
public MemberEntity(String memberId, String password, String memberName, String email, String phone, String zipCode,
String address1, String address2, LocalDate birthday) {
this.memberId = memberId;
this.password = password;
this.memberName = memberName;
this.email = email;
this.phone = phone;
this.zipCode = zipCode;
this.address1 = address1;
this.address2 = address2;
this.birthday = birthday;
}
}

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

@@ -0,0 +1,41 @@
package kiz.app.member.adapter.out.persistence.mapper;
import org.springframework.stereotype.Component;
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;
import kiz.app.member.domain.Phone;
@Component
public class MemberMapper {
public Member toDomain(MemberQueryEntity member) {
return Member.builder()
.memberId(member.getMemberId())
.password(member.getPassword())
.memberName(member.getMemberName())
.email(Email.of(member.getEmail()))
.phone(Phone.of(member.getPhone()))
.address(Address.of(member.getZipCode(), member.getAddress1(), member.getAddress2()))
.birthday(member.getBirthday())
.build();
}
public MemberEntity toEntity(Member member) {
return MemberEntity.builder()
.memberId(member.getMemberId())
.password(member.getPassword())
.memberName(member.getMemberName())
.email(member.getEmail().getValue())
.phone(member.getPhone().getValue())
.zipCode(member.getAddress().getZipCode())
.address1(member.getAddress().getAddress1())
.address2(member.getAddress().getAddress2())
.birthday(member.getBirthday())
.build();
}
}

View File

@@ -0,0 +1,9 @@
package kiz.app.member.adapter.out.persistence.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import kiz.app.member.adapter.out.persistence.entity.MemberEntity;
public interface MemberJpaRepository extends JpaRepository<MemberEntity, Long> {
}

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

@@ -0,0 +1,13 @@
package kiz.app.member.application.port.in;
import java.util.List;
import kiz.app.member.domain.Member;
public interface FindMemberQuery {
Member getMember(String memberId);
List<Member> getMembers();
}

View File

@@ -0,0 +1,10 @@
package kiz.app.member.application.port.in;
import kiz.app.member.application.port.in.command.SignUpCommand;
import kiz.app.member.domain.Member.MemberId;
public interface SignUpUseCase {
MemberId signUp(SignUpCommand command);
}

View File

@@ -0,0 +1,15 @@
package kiz.app.member.application.port.in.command;
import java.time.LocalDate;
public record SignUpCommand (
String memberId,
String password,
String memberName,
String email,
String phone,
String zipCode,
String address1,
String address2,
LocalDate birthday
) {}

View File

@@ -0,0 +1,13 @@
package kiz.app.member.application.port.out;
import java.util.List;
import kiz.app.member.domain.Member;
public interface FindMemberPort {
Member findByMemberId(String memberId);
List<Member> findAll();
}

View File

@@ -0,0 +1,10 @@
package kiz.app.member.application.port.out;
import kiz.app.member.domain.Member;
import kiz.app.member.domain.Member.MemberId;
public interface SignUpPort {
MemberId signUp(Member member);
}

View File

@@ -0,0 +1,27 @@
package kiz.app.member.application.service;
import java.util.List;
import kiz.app.common.UseCase;
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 FindMemberQuery {
private final FindMemberPort findMemberPort;
@Override
public Member getMember(String memberId) {
return findMemberPort.findByMemberId(memberId);
}
@Override
public List<Member> getMembers() {
return findMemberPort.findAll();
}
}

View File

@@ -0,0 +1,36 @@
package kiz.app.member.application.service;
import org.springframework.security.crypto.password.PasswordEncoder;
import kiz.app.common.UseCase;
import kiz.app.member.application.port.in.SignUpUseCase;
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(access = AccessLevel.PRIVATE)
@UseCase
public class SignUpService implements SignUpUseCase {
private final SignUpPort signUpPort;
private final PasswordEncoder passwordEncoder;
@Override
public MemberId signUp(final SignUpCommand command) {
return signUpPort.signUp(
Member.createMember(
command.memberId(),
passwordEncoder.encode(command.password()),
command.memberName(),
command.email(),
command.phone(),
command.zipCode(),
command.address1(),
command.address2(),
command.birthday()));
}
}

View File

@@ -0,0 +1,20 @@
package kiz.app.member.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Address {
@Getter private final String zipCode;
@Getter private final String address1;
@Getter private final String address2;
public static Address of(String zipCode, String address1, String address2) {
return new Address(zipCode, address1, address2);
}
}

View File

@@ -0,0 +1,17 @@
package kiz.app.member.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Email {
@Getter private final String value;
public static Email of(String value) {
return new Email(value);
}
}

View File

@@ -0,0 +1,57 @@
package kiz.app.member.domain;
import java.time.LocalDate;
import java.util.Optional;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Value;
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Member {
@Value
public static class MemberId {
private Long value;
}
private final MemberId id;
public Optional<MemberId> getId(){
return Optional.ofNullable(this.id);
}
@Getter private final String memberId;
@Getter private final String password;
@Getter private final String memberName;
@Getter private final Email email;
@Getter private final Phone phone;
@Getter private final Address address;
@Getter private final LocalDate birthday;
public static Member createMember(
final String memberId,
final String password,
final String memberName,
final String email,
final String phone,
final String zipCode,
final String address1,
final String address2,
final LocalDate birthday
) {
return Member.builder()
.memberId(memberId)
.password(password)
.memberName(memberName)
.email(Email.of(email))
.phone(Phone.of(phone))
.address(Address.of(zipCode, address1, address2))
.birthday(birthday)
.build();
}
}

View File

@@ -0,0 +1,18 @@
package kiz.app.member.domain;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@EqualsAndHashCode
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Phone {
@Getter private final String value;
public static Phone of(String value) {
return new Phone(value);
}
}

View File

@@ -0,0 +1,69 @@
server:
port: 0
# servlet:
# contextPath: /member
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
# path: /h2-console
# settings:
# web-allow-others: true
datasource:
url: jdbc:mariadb://mindol.synology.me:3307/kiz_space
driver-class-name: org.mariadb.jdbc.Driver
username: mindolangel
password: $awlswn1318A
# driver-class-name: org.h2.Driver
# url: jdbc:h2:mem:userdb;DB_CLOSE_DELAY=-1
# username: sa
# password:
jpa:
open-in-view: false
generate-ddl: true
show-sql: true
hibernate: # hibernate 사용 설정
# 애플리케이션 실행 시점에 테이블을 다 지우고, 내가 가진 entity 정보를 보고 다시 테이블 자동 생성
# if exists drop table 해주고 다시 만들어준다고 보면 된다.
ddl-auto: update
properties: # property 사용 설정
hibernate: # hibernate property 설정
ogm:
datastore:
create:
database: true
format-sql: true
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
shutdown:
enabled: true
logging:
level:
kiz:
app: DEBUG
org:
hibernate:
SQL: debug
type: trace

View File

@@ -0,0 +1,27 @@
spring:
application:
name: member-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 kiz.space.kiz;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KizApplicationTests {
@Test
void contextLoads() {
}
}