diff --git a/sleuth-sqs-poc/.gitignore b/sleuth-sqs-poc/.gitignore new file mode 100644 index 0000000..c61597b --- /dev/null +++ b/sleuth-sqs-poc/.gitignore @@ -0,0 +1,28 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +### ETC ### +.DS_Store diff --git a/sleuth-sqs-poc/Makefile b/sleuth-sqs-poc/Makefile new file mode 100644 index 0000000..4cdeb6d --- /dev/null +++ b/sleuth-sqs-poc/Makefile @@ -0,0 +1,13 @@ +## COMMANDS + +start-app: + docker-compose up + +stop-app: + docker-compose down + +start-zipkin: + docker-compose up -d zipkin-server + +stop-zipkin: + docker-compose down \ No newline at end of file diff --git a/sleuth-sqs-poc/README.md b/sleuth-sqs-poc/README.md new file mode 100644 index 0000000..01aa506 --- /dev/null +++ b/sleuth-sqs-poc/README.md @@ -0,0 +1,30 @@ +# Sleuth AWS SQS POC + +해당 프로젝트는 Slueth(Zipkin) 를 통한 메시지 추적 POC(Proof of concept) 입니다.
+Rest API 를 통해 POST 요청을 받으면, 메시지를 발행/소비 합니다. 이 과정에서 유지되는 TraceId 를 확인합니다.
+
+ +This project is a Proof of Concept that tracks messages through Sleuth(Zipkin).
+When a POST request is received through the Rest API, the message is published/consumed. Check the TraceId maintained during this process.
+
+ +## Diagram +image + +## Run +### Clone project +``` +$ git clone https://github.com/currenjin/sleuth-sqs-poc +``` + +### Run container +``` +$ make start-app +``` + +*jar is required. + +### Invoke api +``` +$ curl --request POST --data 'test' http://localhost:5000/post +``` diff --git a/sleuth-sqs-poc/delivery/.gitignore b/sleuth-sqs-poc/delivery/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/sleuth-sqs-poc/delivery/.gitignore @@ -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/ diff --git a/sleuth-sqs-poc/delivery/Dockerfile b/sleuth-sqs-poc/delivery/Dockerfile new file mode 100644 index 0000000..faa2310 --- /dev/null +++ b/sleuth-sqs-poc/delivery/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8-jdk-alpine + +COPY ./build/libs/delivery.jar app.jar + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/sleuth-sqs-poc/delivery/build.gradle b/sleuth-sqs-poc/delivery/build.gradle new file mode 100644 index 0000000..5368045 --- /dev/null +++ b/sleuth-sqs-poc/delivery/build.gradle @@ -0,0 +1,21 @@ +plugins { + id "org.springframework.boot" version "2.3.4.RELEASE" + id "io.spring.dependency-management" version "1.0.11.RELEASE" + id 'java' +} + +sourceCompatibility = '1.8' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.cloud:spring-cloud-aws-messaging:2.2.6.RELEASE' + implementation 'org.springframework.cloud:spring-cloud-aws-autoconfigure:2.2.6.RELEASE' + + implementation 'org.springframework.cloud:spring-cloud-starter-sleuth:2.2.8.RELEASE' + implementation 'org.springframework.cloud:spring-cloud-sleuth-zipkin:2.2.8.RELEASE' + + implementation 'io.zipkin.aws:brave-instrumentation-aws-java-sdk-sqs:0.23.4' +} diff --git a/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.jar b/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.properties b/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..00e33ed --- /dev/null +++ b/sleuth-sqs-poc/delivery/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sleuth-sqs-poc/delivery/gradlew b/sleuth-sqs-poc/delivery/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/sleuth-sqs-poc/delivery/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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" "$@" diff --git a/sleuth-sqs-poc/delivery/gradlew.bat b/sleuth-sqs-poc/delivery/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/sleuth-sqs-poc/delivery/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sleuth-sqs-poc/delivery/settings.gradle b/sleuth-sqs-poc/delivery/settings.gradle new file mode 100644 index 0000000..6a6c7ab --- /dev/null +++ b/sleuth-sqs-poc/delivery/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'delivery' diff --git a/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/App.java b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/App.java new file mode 100644 index 0000000..03cfbba --- /dev/null +++ b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/App.java @@ -0,0 +1,14 @@ +package com.trevari.zipkinpoc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration; + +@SpringBootApplication(exclude = ContextInstanceDataAutoConfiguration.class) +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + +} diff --git a/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java new file mode 100644 index 0000000..5c0f041 --- /dev/null +++ b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java @@ -0,0 +1,37 @@ +package com.trevari.zipkinpoc.config; + +import brave.Tracer; +import brave.Tracing; +import brave.instrumentation.aws.sqs.SqsMessageTracing; +import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.sqs.AmazonSQSAsync; +import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class QueueConfig { + + Tracer tracer; + + public QueueConfig(Tracer tracer) { + this.tracer = tracer; + } + + @Bean + public QueueMessagingTemplate queueMessagingTemplate() { + Tracing current = Tracing.current(); + SqsMessageTracing sqsMessageTracing = SqsMessageTracing.create(current); + + AmazonSQSAsync client = AmazonSQSAsyncClientBuilder.standard() + .withRegion(Regions.AP_NORTHEAST_2) + .withCredentials(new EnvironmentVariableCredentialsProvider()) + .withRequestHandlers(sqsMessageTracing.requestHandler()) + .build(); + + return new QueueMessagingTemplate(client); + } + +} \ No newline at end of file diff --git a/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/consume/Consumer.java b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/consume/Consumer.java new file mode 100644 index 0000000..441fe2b --- /dev/null +++ b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/consume/Consumer.java @@ -0,0 +1,30 @@ +package com.trevari.zipkinpoc.consume; + +import com.amazonaws.services.sns.model.MessageAttributeValue; +import com.trevari.zipkinpoc.publish.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cloud.aws.messaging.listener.annotation.SqsListener; +import org.springframework.messaging.handler.annotation.Headers; +import org.springframework.stereotype.Service; + +import java.util.Map; + +@Service +public class Consumer { + + private final Logger logger = LoggerFactory.getLogger(Consumer.class); + private final Publisher publisher; + + public Consumer(Publisher publisher) { + this.publisher = publisher; + } + + @SqsListener("${post.queue.name}") + public void receiveMessage(String message, @Headers Map sqsHeaders) { + logger.info("[배송 요청 발생]"); + logger.info("내용 : " + message); + + publisher.send(message); + } +} diff --git a/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java new file mode 100644 index 0000000..ec36c74 --- /dev/null +++ b/sleuth-sqs-poc/delivery/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java @@ -0,0 +1,29 @@ +package com.trevari.zipkinpoc.publish; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.stereotype.Service; + +@Service +public class Publisher { + + private final Logger logger = LoggerFactory.getLogger(Publisher.class); + + @Value("${delivery.queue.name}") + private String queueName; + + private final QueueMessagingTemplate messagingTemplate; + + public Publisher(QueueMessagingTemplate messagingTemplate) { + this.messagingTemplate = messagingTemplate; + } + + public void send(Object message) { + messagingTemplate.convertAndSend(queueName, message); + + logger.info("[배송 완료]"); + } + +} \ No newline at end of file diff --git a/sleuth-sqs-poc/delivery/src/main/resources/application.yml b/sleuth-sqs-poc/delivery/src/main/resources/application.yml new file mode 100644 index 0000000..82f541f --- /dev/null +++ b/sleuth-sqs-poc/delivery/src/main/resources/application.yml @@ -0,0 +1,22 @@ +spring: + application: + name: delivery + + zipkin: + base-url: ${ZIPKIN_URL} + +cloud: + aws: + credentials: + accessKey: ${AWS_ACCESS_KEY_ID} + secretKey: ${AWS_SECRET_ACCESS_KEY} + + region: + auto: false + static: ap-northeast-2 + + stack: + auto: false + +post.queue.name: ${POST_QUEUE_NAME} +delivery.queue.name: ${DELIVERY_QUEUE_NAME} diff --git a/sleuth-sqs-poc/docker-compose.yml b/sleuth-sqs-poc/docker-compose.yml new file mode 100644 index 0000000..9f0c5ab --- /dev/null +++ b/sleuth-sqs-poc/docker-compose.yml @@ -0,0 +1,38 @@ +# docker-compose.yml + +version: "3" +services: + post: + container_name: post + restart: always + ports: + - "5000:8080" + environment: + - POST_QUEUE_NAME + - AWS_ACCESS_KEY_ID + - AWS_SECRET_ACCESS_KEY + - ZIPKIN_URL=http://host.docker.internal:9411 + build: + context: ./post/ + dockerfile: Dockerfile + + delivery: + container_name: delivery + restart: always + ports: + - "5001:8080" + environment: + - POST_QUEUE_NAME + - DELIVERY_QUEUE_NAME + - AWS_ACCESS_KEY_ID + - AWS_SECRET_ACCESS_KEY + - ZIPKIN_URL=http://host.docker.internal:9411 + build: + context: ./delivery/ + dockerfile: Dockerfile + zipkin-server: + container_name: zipkin-server + image: openzipkin/zipkin + restart: always + ports: + - "9411:9411" \ No newline at end of file diff --git a/sleuth-sqs-poc/post/.gitignore b/sleuth-sqs-poc/post/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/sleuth-sqs-poc/post/.gitignore @@ -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/ diff --git a/sleuth-sqs-poc/post/Dockerfile b/sleuth-sqs-poc/post/Dockerfile new file mode 100644 index 0000000..2296c5e --- /dev/null +++ b/sleuth-sqs-poc/post/Dockerfile @@ -0,0 +1,5 @@ +FROM openjdk:8-jdk-alpine + +COPY ./build/libs/post.jar app.jar + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/sleuth-sqs-poc/post/build.gradle b/sleuth-sqs-poc/post/build.gradle new file mode 100644 index 0000000..902e74a --- /dev/null +++ b/sleuth-sqs-poc/post/build.gradle @@ -0,0 +1,24 @@ +plugins { + id "org.springframework.boot" version "2.3.4.RELEASE" + id "io.spring.dependency-management" version "1.0.11.RELEASE" + id 'java' +} + +sourceCompatibility = '1.8' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.cloud:spring-cloud-aws-messaging:2.2.6.RELEASE' + implementation 'org.springframework.cloud:spring-cloud-aws-autoconfigure:2.2.6.RELEASE' + + implementation 'org.springframework.cloud:spring-cloud-starter-sleuth:2.2.8.RELEASE' + implementation 'org.springframework.cloud:spring-cloud-sleuth-zipkin:2.2.8.RELEASE' + + implementation 'io.zipkin.aws:brave-instrumentation-aws-java-sdk-sqs:0.23.4' + + implementation 'org.springframework.boot:spring-boot-starter-web:2.3.4.RELEASE' +} + diff --git a/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.jar b/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.properties b/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..00e33ed --- /dev/null +++ b/sleuth-sqs-poc/post/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sleuth-sqs-poc/post/gradlew b/sleuth-sqs-poc/post/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/sleuth-sqs-poc/post/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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" "$@" diff --git a/sleuth-sqs-poc/post/gradlew.bat b/sleuth-sqs-poc/post/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/sleuth-sqs-poc/post/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sleuth-sqs-poc/post/settings.gradle b/sleuth-sqs-poc/post/settings.gradle new file mode 100644 index 0000000..9f03055 --- /dev/null +++ b/sleuth-sqs-poc/post/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'post' diff --git a/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/App.java b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/App.java new file mode 100644 index 0000000..ad30946 --- /dev/null +++ b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/App.java @@ -0,0 +1,13 @@ +package com.trevari.zipkinpoc; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class App { + + public static void main(String[] args) { + SpringApplication.run(App.class, args); + } + +} diff --git a/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/api/PostController.java b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/api/PostController.java new file mode 100644 index 0000000..05f5d66 --- /dev/null +++ b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/api/PostController.java @@ -0,0 +1,29 @@ +package com.trevari.zipkinpoc.api; + +import com.trevari.zipkinpoc.publish.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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; + +@RestController +@RequestMapping("/post") +public class PostController { + + private final Logger logger = LoggerFactory.getLogger(PostController.class); + private final Publisher publisher; + + public PostController(Publisher publisher) { + this.publisher = publisher; + } + + @PostMapping + public void sendMessage(@RequestBody String message) { + logger.info("[우편 발송 요청]"); + logger.info("내용 : " + message); + + publisher.send(message); + } +} \ No newline at end of file diff --git a/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java new file mode 100644 index 0000000..5c0f041 --- /dev/null +++ b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/config/QueueConfig.java @@ -0,0 +1,37 @@ +package com.trevari.zipkinpoc.config; + +import brave.Tracer; +import brave.Tracing; +import brave.instrumentation.aws.sqs.SqsMessageTracing; +import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; +import com.amazonaws.regions.Regions; +import com.amazonaws.services.sqs.AmazonSQSAsync; +import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class QueueConfig { + + Tracer tracer; + + public QueueConfig(Tracer tracer) { + this.tracer = tracer; + } + + @Bean + public QueueMessagingTemplate queueMessagingTemplate() { + Tracing current = Tracing.current(); + SqsMessageTracing sqsMessageTracing = SqsMessageTracing.create(current); + + AmazonSQSAsync client = AmazonSQSAsyncClientBuilder.standard() + .withRegion(Regions.AP_NORTHEAST_2) + .withCredentials(new EnvironmentVariableCredentialsProvider()) + .withRequestHandlers(sqsMessageTracing.requestHandler()) + .build(); + + return new QueueMessagingTemplate(client); + } + +} \ No newline at end of file diff --git a/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java new file mode 100644 index 0000000..4109330 --- /dev/null +++ b/sleuth-sqs-poc/post/src/main/java/com/trevari/zipkinpoc/publish/Publisher.java @@ -0,0 +1,29 @@ +package com.trevari.zipkinpoc.publish; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cloud.aws.messaging.core.QueueMessagingTemplate; +import org.springframework.stereotype.Service; + +@Service +public class Publisher { + + private final Logger logger = LoggerFactory.getLogger(Publisher.class); + + @Value("${post.queue.name}") + private String queueName; + + private final QueueMessagingTemplate messagingTemplate; + + public Publisher(QueueMessagingTemplate messagingTemplate) { + this.messagingTemplate = messagingTemplate; + } + + public void send(Object message) { + messagingTemplate.convertAndSend(queueName, message); + + logger.info("[우편 발송 요청 완료]"); + } + +} \ No newline at end of file diff --git a/sleuth-sqs-poc/post/src/main/resources/application.yml b/sleuth-sqs-poc/post/src/main/resources/application.yml new file mode 100644 index 0000000..363c7aa --- /dev/null +++ b/sleuth-sqs-poc/post/src/main/resources/application.yml @@ -0,0 +1,23 @@ +spring: + application: + name: post + + zipkin: + base-url: ${ZIPKIN_URL} + +cloud: + aws: + credentials: + accessKey: ${AWS_ACCESS_KEY_ID} + secretKey: ${AWS_SECRET_ACCESS_KEY} + + region: + auto: false + static: ap-northeast-2 + + stack: + auto: false + +post.queue.name: ${POST_QUEUE_NAME} + +logging.level.com.amazonaws.util.EC2MetadataUtils: error diff --git a/spring-data-elasticsearch-poc/.gitignore b/spring-data-elasticsearch-poc/.gitignore new file mode 100644 index 0000000..309c3db --- /dev/null +++ b/spring-data-elasticsearch-poc/.gitignore @@ -0,0 +1,28 @@ +.gradle +/build/ +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +### ETC ### +.DS_Store \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/Makefile b/spring-data-elasticsearch-poc/Makefile new file mode 100644 index 0000000..24f9f95 --- /dev/null +++ b/spring-data-elasticsearch-poc/Makefile @@ -0,0 +1,13 @@ +## COMMANDS + +start-elasticsearch: + docker-compose up elasticsearch-server user-for-elasticsearch + +stop-elasticsearch: + docker-compose down + +start-opensearch: + docker-compose up user-for-opensearch + +stop-opensearch: + docker-compose down diff --git a/spring-data-elasticsearch-poc/README.md b/spring-data-elasticsearch-poc/README.md new file mode 100644 index 0000000..8a1b3c1 --- /dev/null +++ b/spring-data-elasticsearch-poc/README.md @@ -0,0 +1,49 @@ +# Spring-Data-Elasticsearch-POC +해당 프로젝트는 Spring Data Elasticsearch 에 대한 Index/Query POC(Proof of concept) 입니다.
+ +아래 서비스에 대한 POC 를 지원합니다. +- Elasticsearch +- Opensearch + +
+ +This project is an Index/Query POC (Proof of Concept) for Spring Data Elasticsearch.
+ +We support POC for the following services: +- Elasticsearch +- Opensearch + +## Diagram + +image + +## Run +### Clone project +```shell +$ https://github.com/currenjin/elasticsearch-poc +``` + +### Elasticsearch +`$ make start-elasticsearch` * jar is required. + +### Opensearch +`$ make start-opensearch` * jar is required. + +### Invoke api +> PORT Number +> - Elasticsearch client : 8081 +> - Opensearch client : 8082 + +#### In(Index) +```shell +$ curl -d '{"id":"test","name":"currenjin","phoneNumber":"01012341234"}' \ +-H "Content-Type: application/json" \ +-X POST http://localhost:{PORT}/ +``` + +#### Out(Query) +```shell +$ curl -X GET "http://localhost:{PORT}/test" +$ curl -X GET "http://localhost:{PORT}?name=currenjin" +$ curl -X GET "http://localhost:{PORT}?phoneNumber=01012341234" +``` diff --git a/spring-data-elasticsearch-poc/docker-compose.yml b/spring-data-elasticsearch-poc/docker-compose.yml new file mode 100644 index 0000000..dd51c5d --- /dev/null +++ b/spring-data-elasticsearch-poc/docker-compose.yml @@ -0,0 +1,39 @@ +# docker-compose.yml + +version: "3" +services: + elasticsearch-server: + container_name: elasticsearch-server + image: elasticsearch:7.6.2 + restart: always + ports: + - "9200:9200" + environment: + - discovery.type=single-node + + user-for-elasticsearch: + container_name: user + restart: always + ports: + - "8081:8080" + environment: + - ELASTICSEARCH_URL=host.docker.internal:9200 + build: + context: ./elasticsearch/ + dockerfile: Dockerfile + + user-for-opensearch: + container_name: user + restart: always + ports: + - "8082:8080" + environment: + - AWS_REGION + - OS_USERNAME + - OS_PASSWORD + - OS_HOST + - OS_PORT=443 + - OS_PROTOCOL=https + build: + context: ./opensearch/ + dockerfile: Dockerfile diff --git a/spring-data-elasticsearch-poc/elasticsearch/Dockerfile b/spring-data-elasticsearch-poc/elasticsearch/Dockerfile new file mode 100644 index 0000000..7355c5e --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/Dockerfile @@ -0,0 +1,5 @@ +FROM adoptopenjdk/openjdk11:jre-11.0.9.1_1-alpine + +COPY ./build/libs/elasticsearch.jar app.jar + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/elasticsearch/build.gradle b/spring-data-elasticsearch-poc/elasticsearch/build.gradle new file mode 100644 index 0000000..521ce8b --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/build.gradle @@ -0,0 +1,18 @@ +plugins { + id 'org.springframework.boot' version '2.6.7' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' +} + +sourceCompatibility = '11' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch' + implementation 'org.springframework.boot:spring-boot-starter-web:2.6.7' + + testImplementation 'org.springframework.boot:spring-boot-starter-test:2.6.7' +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/gradlew b/spring-data-elasticsearch-poc/elasticsearch/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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" "$@" diff --git a/spring-data-elasticsearch-poc/elasticsearch/gradlew.bat b/spring-data-elasticsearch-poc/elasticsearch/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-data-elasticsearch-poc/elasticsearch/settings.gradle b/spring-data-elasticsearch-poc/elasticsearch/settings.gradle new file mode 100644 index 0000000..327d057 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'elasticsearch' diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/ElasticsearchApplication.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/ElasticsearchApplication.java new file mode 100644 index 0000000..134133e --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/ElasticsearchApplication.java @@ -0,0 +1,13 @@ +package com.poc.elasticsearch; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElasticsearchApplication { + + public static void main(String[] args) { + SpringApplication.run(ElasticsearchApplication.class, args); + } + +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserCreator.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserCreator.java new file mode 100644 index 0000000..b3a0d48 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserCreator.java @@ -0,0 +1,26 @@ +package com.poc.elasticsearch.application; + +import com.poc.elasticsearch.domain.User; +import com.poc.elasticsearch.domain.UserRepository; +import org.springframework.stereotype.Service; + +@Service +public class UserCreator { + + private final UserRepository userRepository; + + public void create(User user) { + validateUser(user); + userRepository.save(user); + } + + public UserCreator(UserRepository userRepository) { + this.userRepository = userRepository; + } + + private void validateUser(User user) { + if (user == null) { + throw new IllegalArgumentException(); + } + } +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserFinder.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserFinder.java new file mode 100644 index 0000000..9ff793f --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/application/UserFinder.java @@ -0,0 +1,30 @@ +package com.poc.elasticsearch.application; + +import com.poc.elasticsearch.domain.User; +import com.poc.elasticsearch.domain.UserRepository; +import org.springframework.stereotype.Service; + +@Service +public class UserFinder { + + private final UserRepository userRepository; + + public UserFinder(UserRepository userRepository) { + this.userRepository = userRepository; + } + + public User findById(String id) { + return userRepository.findById(id) + .orElseThrow(IllegalArgumentException::new); + } + + public User findByName(String name) { + return userRepository.findByName(name) + .orElseThrow(IllegalArgumentException::new); + } + + public User findByPhoneNumber(String phoneNumber) { + return userRepository.findByPhoneNumber(phoneNumber) + .orElseThrow(IllegalArgumentException::new); + } +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/config/ElasticsearchConfig.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/config/ElasticsearchConfig.java new file mode 100644 index 0000000..8a5dde2 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/config/ElasticsearchConfig.java @@ -0,0 +1,36 @@ +package com.poc.elasticsearch.config; + +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.elasticsearch.client.ClientConfiguration; +import org.springframework.data.elasticsearch.client.RestClients; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; +import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; + +@Configuration +@EnableElasticsearchRepositories(basePackages = "com.poc.elasticsearch.domain") +@ComponentScan(basePackages = "com.poc.elasticsearch.application") +public class ElasticsearchConfig { + + @Value("${ELASTICSEARCH_URL}") + private String ELASTICSEARCH_URL; + + @Bean + public RestHighLevelClient client() { + ClientConfiguration clientConfiguration = ClientConfiguration.builder() + .connectedTo(ELASTICSEARCH_URL) + .build(); + + return RestClients.create(clientConfiguration).rest(); + } + + @Bean + public ElasticsearchOperations elasticsearchTemplate() { + return new ElasticsearchRestTemplate(client()); + } + +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/User.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/User.java new file mode 100644 index 0000000..6ef5c95 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/User.java @@ -0,0 +1,38 @@ +package com.poc.elasticsearch.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; + +@Document(indexName = "user-index") +public class User { + + @Id + private String id; + + @Field(type = FieldType.Text, name = "name") + private String name; + + @Field(type = FieldType.Text, name = "phoneNumber") + private String phoneNumber; + + public User(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } + +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/UserRepository.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/UserRepository.java new file mode 100644 index 0000000..efa847b --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/domain/UserRepository.java @@ -0,0 +1,10 @@ +package com.poc.elasticsearch.domain; + +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +import java.util.Optional; + +public interface UserRepository extends ElasticsearchRepository { + Optional findByName(String name); + Optional findByPhoneNumber(String phoneNumber); +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserGetController.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserGetController.java new file mode 100644 index 0000000..8075f50 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserGetController.java @@ -0,0 +1,40 @@ +package com.poc.elasticsearch.presentation; + +import com.poc.elasticsearch.application.UserFinder; +import com.poc.elasticsearch.domain.User; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserGetController { + + private final UserFinder userFinder; + + public UserGetController(UserFinder userFinder) { + this.userFinder = userFinder; + } + + @GetMapping(value = "/{userId}") + public UserResponse getUserById(@PathVariable String userId) { + User user = userFinder.findById(userId); + return convertToUserResponseBy(user); + } + + @GetMapping(params = "name") + public UserResponse getUserByName(@RequestParam(value = "name") String name) { + User user = userFinder.findByName(name); + return convertToUserResponseBy(user); + } + + @GetMapping(params = "phoneNumber") + public UserResponse getUserByPhoneNumber(@RequestParam(value = "phoneNumber") String phoneNumber) { + User user = userFinder.findByPhoneNumber(phoneNumber); + return convertToUserResponseBy(user); + } + + private UserResponse convertToUserResponseBy(User user) { + return new UserResponse(user.getId(), user.getName(), user.getPhoneNumber()); + } +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostController.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostController.java new file mode 100644 index 0000000..5dd3d68 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostController.java @@ -0,0 +1,24 @@ +package com.poc.elasticsearch.presentation; + +import com.poc.elasticsearch.application.UserCreator; +import com.poc.elasticsearch.domain.User; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserPostController { + + private final UserCreator userCreator; + + public UserPostController(UserCreator userCreator) { + this.userCreator = userCreator; + } + + @PostMapping + public void postUser(@RequestBody UserPostRequest request) { + User user = new User(request.getId(), request.getName(), request.getPhoneNumber()); + userCreator.create(user); + } + +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostRequest.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostRequest.java new file mode 100644 index 0000000..29cefbb --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserPostRequest.java @@ -0,0 +1,25 @@ +package com.poc.elasticsearch.presentation; + +public class UserPostRequest { + private final String id; + private final String name; + private final String phoneNumber; + + public UserPostRequest(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserResponse.java b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserResponse.java new file mode 100644 index 0000000..9c26f2d --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/java/com/poc/elasticsearch/presentation/UserResponse.java @@ -0,0 +1,25 @@ +package com.poc.elasticsearch.presentation; + +public class UserResponse { + private final String id; + private final String name; + private final String phoneNumber; + + public UserResponse(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/main/resources/application.yml b/spring-data-elasticsearch-poc/elasticsearch/src/main/resources/application.yml new file mode 100644 index 0000000..1e694cf --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/main/resources/application.yml @@ -0,0 +1,4 @@ +server: + port: 8080 + +ELASTICSEARCH_URL: ${ELASTICSEARCH_URL} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/ElasticsearchApplicationTests.java b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/ElasticsearchApplicationTests.java new file mode 100644 index 0000000..ecb66e0 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/ElasticsearchApplicationTests.java @@ -0,0 +1,13 @@ +package com.poc.elasticsearch; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ElasticsearchApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserCreatorTest.java b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserCreatorTest.java new file mode 100644 index 0000000..a42cda6 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserCreatorTest.java @@ -0,0 +1,39 @@ +package com.poc.elasticsearch.application; + +import com.poc.elasticsearch.domain.User; +import com.poc.elasticsearch.domain.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class UserCreatorTest { + User user = new User("S", "S", "S"); + + @Mock + UserRepository repository; + + UserCreator sut; + + @BeforeEach + void setUp() { + sut = new UserCreator(repository); + } + + @Test + void 유저를_생성합니다() { + sut.create(user); + + verify(repository).save(user); + } + + @Test + void 유효하지_않은_유저를_전달하면_예외가_발생합니다() { + assertThatThrownBy(() -> sut.create(null)).isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserFinderTest.java b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserFinderTest.java new file mode 100644 index 0000000..f603b79 --- /dev/null +++ b/spring-data-elasticsearch-poc/elasticsearch/src/test/java/com/poc/elasticsearch/application/UserFinderTest.java @@ -0,0 +1,82 @@ +package com.poc.elasticsearch.application; + +import com.poc.elasticsearch.domain.User; +import com.poc.elasticsearch.domain.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class UserFinderTest { + + private static final String ANY_STRING = "String"; + + @Mock + UserRepository repository; + + @Mock + private User user; + + UserFinder sut; + + @BeforeEach + void setUp() { + sut = new UserFinder(repository); + } + + @Test + void ID_로_조회_시_유저가_없으면_예외가_발생한다() { + given(repository.findById(ANY_STRING)).willReturn(Optional.empty()); + + assertThatThrownBy(() -> sut.findById(ANY_STRING)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void NAME_으로_조회_시_유저가_없으면_예외가_발생한다() { + given(repository.findByName(ANY_STRING)).willReturn(Optional.empty()); + + assertThatThrownBy(() -> sut.findByName(ANY_STRING)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void PHONE_NUMBER_로_조회_시_유저가_없으면_예외가_발생한다() { + given(repository.findByPhoneNumber(ANY_STRING)).willReturn(Optional.empty()); + + assertThatThrownBy(() -> sut.findByPhoneNumber(ANY_STRING)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void ID_로_조회한다() { + given(repository.findById(ANY_STRING)).willReturn(Optional.of(user)); + + sut.findById(ANY_STRING); + + verify(repository).findById(ANY_STRING); + } + + @Test + void NAME_으로_조회한다() { + given(repository.findByName(ANY_STRING)).willReturn(Optional.of(user)); + + sut.findByName(ANY_STRING); + + verify(repository).findByName(ANY_STRING); + } + + @Test + void PHONE_NUMBER_로_조회한다() { + given(repository.findByPhoneNumber(ANY_STRING)).willReturn(Optional.of(user)); + + sut.findByPhoneNumber(ANY_STRING); + + verify(repository).findByPhoneNumber(ANY_STRING); + } +} \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/opensearch/Dockerfile b/spring-data-elasticsearch-poc/opensearch/Dockerfile new file mode 100644 index 0000000..a2a84f4 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/Dockerfile @@ -0,0 +1,5 @@ +FROM adoptopenjdk/openjdk11:jre-11.0.9.1_1-alpine + +COPY ./build/libs/opensearch.jar app.jar + +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/opensearch/build.gradle b/spring-data-elasticsearch-poc/opensearch/build.gradle new file mode 100644 index 0000000..2b54233 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/build.gradle @@ -0,0 +1,21 @@ +plugins { + id 'org.springframework.boot' version '2.5.5' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' +} + +sourceCompatibility = '11' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch' + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +test { + useJUnitPlatform() +} diff --git a/spring-data-elasticsearch-poc/opensearch/gradlew b/spring-data-elasticsearch-poc/opensearch/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/gradlew @@ -0,0 +1,234 @@ +#!/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 \ + "$@" + +# 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" "$@" diff --git a/spring-data-elasticsearch-poc/opensearch/gradlew.bat b/spring-data-elasticsearch-poc/opensearch/gradlew.bat new file mode 100644 index 0000000..ac1b06f --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/gradlew.bat @@ -0,0 +1,89 @@ +@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%" == "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%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-data-elasticsearch-poc/opensearch/settings.gradle b/spring-data-elasticsearch-poc/opensearch/settings.gradle new file mode 100644 index 0000000..c7b19f0 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'opensearch' diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/ElasticsearchApplication.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/ElasticsearchApplication.java new file mode 100644 index 0000000..9476a21 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/ElasticsearchApplication.java @@ -0,0 +1,13 @@ +package com.poc.opensearch; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ElasticsearchApplication { + + public static void main(String[] args) { + SpringApplication.run(ElasticsearchApplication.class, args); + } + +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserCreator.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserCreator.java new file mode 100644 index 0000000..92e8d3e --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserCreator.java @@ -0,0 +1,26 @@ +package com.poc.opensearch.application; + +import com.poc.opensearch.domain.User; +import com.poc.opensearch.domain.UserRepository; +import org.springframework.stereotype.Service; + +@Service +public class UserCreator { + + private final UserRepository userRepository; + + public void create(User user) { + validateUser(user); + userRepository.save(user); + } + + public UserCreator(UserRepository userRepository) { + this.userRepository = userRepository; + } + + private void validateUser(User user) { + if (user == null) { + throw new IllegalArgumentException(); + } + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserFinder.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserFinder.java new file mode 100644 index 0000000..8dddb8e --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/application/UserFinder.java @@ -0,0 +1,30 @@ +package com.poc.opensearch.application; + +import com.poc.opensearch.domain.User; +import com.poc.opensearch.domain.UserRepository; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class UserFinder { + + private final UserRepository userRepository; + + public UserFinder(UserRepository userRepository) { + this.userRepository = userRepository; + } + + public User findById(String id) { + return userRepository.findById(id) + .orElseThrow(IllegalArgumentException::new); + } + + public List findAllByName(String name) { + return userRepository.findAllByNameContaining(name); + } + + public List findAllByPhoneNumber(String phoneNumber) { + return userRepository.findAllByPhoneNumberContaining(phoneNumber); + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/config/ElasticsearchConfig.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/config/ElasticsearchConfig.java new file mode 100644 index 0000000..7a52a6f --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/config/ElasticsearchConfig.java @@ -0,0 +1,49 @@ +package com.poc.opensearch.config; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.elasticsearch.client.RestHighLevelClient; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; + +@Configuration +@EnableElasticsearchRepositories(basePackages = "com.poc.opensearch.domain") +@ComponentScan(basePackages = "com.poc.opensearch.application") +public class ElasticsearchConfig { + + @Value("${cloud.aws.opensearch.credentials.username}") + private String osUsername; + + @Value("${cloud.aws.opensearch.credentials.password}") + private String osPassword; + + @Value("${cloud.aws.opensearch.domain.host}") + private String osHost; + + @Value("${cloud.aws.opensearch.domain.port}") + private Integer osPort; + + @Value("${cloud.aws.opensearch.domain.protocol}") + private String osProtocol; + + @Bean + public RestHighLevelClient openSearchClient() { + return new RestHighLevelClient(getRestClientBuilder()); + } + + private RestClientBuilder getRestClientBuilder() { + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(osUsername, osPassword)); + + return RestClient.builder(new HttpHost(osHost, osPort, osProtocol)) + .setHttpClientConfigCallback(cb -> cb.setDefaultCredentialsProvider(credentialsProvider)); + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/User.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/User.java new file mode 100644 index 0000000..396edd0 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/User.java @@ -0,0 +1,38 @@ +package com.poc.opensearch.domain; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; + +@Document(indexName = "user-index") +public class User { + + @Id + private String id; + + @Field(type = FieldType.Text, name = "name") + private String name; + + @Field(type = FieldType.Text, name = "phoneNumber") + private String phoneNumber; + + public User(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } + +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/UserRepository.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/UserRepository.java new file mode 100644 index 0000000..a22aebc --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/domain/UserRepository.java @@ -0,0 +1,10 @@ +package com.poc.opensearch.domain; + +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + +import java.util.List; + +public interface UserRepository extends ElasticsearchRepository { + List findAllByNameContaining(String name); + List findAllByPhoneNumberContaining(String phoneNumber); +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserGetController.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserGetController.java new file mode 100644 index 0000000..9cb2c10 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserGetController.java @@ -0,0 +1,51 @@ +package com.poc.opensearch.presentation; + +import com.poc.opensearch.application.UserFinder; +import com.poc.opensearch.domain.User; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.ArrayList; +import java.util.List; + +@RestController +public class UserGetController { + + private final UserFinder userFinder; + + public UserGetController(UserFinder userFinder) { + this.userFinder = userFinder; + } + + @GetMapping(value = "/{userId}") + public UserResponse getUserById(@PathVariable String userId) { + User user = userFinder.findById(userId); + return convertToUserResponseBy(user); + } + + @GetMapping(params = "name") + public List getUserByName(@RequestParam(value = "name") String name) { + List users = userFinder.findAllByName(name); + return convertToUserResponseBy(users); + } + + @GetMapping(params = "phoneNumber") + public List getUserByPhoneNumber(@RequestParam(value = "phoneNumber") String phoneNumber) { + List users = userFinder.findAllByPhoneNumber(phoneNumber); + return convertToUserResponseBy(users); + } + + private UserResponse convertToUserResponseBy(User user) { + return new UserResponse(user.getId(), user.getName(), user.getPhoneNumber()); + } + + private List convertToUserResponseBy(List users) { + List userResponseList = new ArrayList<>(); + + users.forEach(e -> userResponseList.add(new UserResponse(e.getId(), e.getName(), e.getPhoneNumber()))); + + return userResponseList; + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostController.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostController.java new file mode 100644 index 0000000..1025cb4 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostController.java @@ -0,0 +1,24 @@ +package com.poc.opensearch.presentation; + +import com.poc.opensearch.application.UserCreator; +import com.poc.opensearch.domain.User; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserPostController { + + private final UserCreator userCreator; + + public UserPostController(UserCreator userCreator) { + this.userCreator = userCreator; + } + + @PostMapping + public void postUser(@RequestBody UserPostRequest request) { + User user = new User(request.getId(), request.getName(), request.getPhoneNumber()); + userCreator.create(user); + } + +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostRequest.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostRequest.java new file mode 100644 index 0000000..8f1fbde --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserPostRequest.java @@ -0,0 +1,25 @@ +package com.poc.opensearch.presentation; + +public class UserPostRequest { + private final String id; + private final String name; + private final String phoneNumber; + + public UserPostRequest(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserResponse.java b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserResponse.java new file mode 100644 index 0000000..e38809f --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/java/com/poc/opensearch/presentation/UserResponse.java @@ -0,0 +1,25 @@ +package com.poc.opensearch.presentation; + +public class UserResponse { + private final String id; + private final String name; + private final String phoneNumber; + + public UserResponse(String id, String name, String phoneNumber) { + this.id = id; + this.name = name; + this.phoneNumber = phoneNumber; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPhoneNumber() { + return phoneNumber; + } +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/main/resources/application.yml b/spring-data-elasticsearch-poc/opensearch/src/main/resources/application.yml new file mode 100644 index 0000000..7baa873 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/main/resources/application.yml @@ -0,0 +1,14 @@ +server: + port: 8080 + +cloud: + aws: + opensearch: + region: ${AWS_REGION} + credentials: + username: ${OS_USERNAME} + password: ${OS_PASSWORD} + domain: + host: ${OS_HOST} + port: ${OS_PORT} + protocol: ${OS_PROTOCOL} \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/ElasticsearchApplicationTests.java b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/ElasticsearchApplicationTests.java new file mode 100644 index 0000000..c986e45 --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/ElasticsearchApplicationTests.java @@ -0,0 +1,13 @@ +package com.poc.opensearch; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ElasticsearchApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserCreatorTest.java b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserCreatorTest.java new file mode 100644 index 0000000..09ff9fa --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserCreatorTest.java @@ -0,0 +1,39 @@ +package com.poc.opensearch.application; + +import com.poc.opensearch.domain.User; +import com.poc.opensearch.domain.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class UserCreatorTest { + User user = new User("S", "S", "S"); + + @Mock + UserRepository repository; + + UserCreator sut; + + @BeforeEach + void setUp() { + sut = new UserCreator(repository); + } + + @Test + void 유저를_생성합니다() { + sut.create(user); + + verify(repository).save(user); + } + + @Test + void 유효하지_않은_유저를_전달하면_예외가_발생합니다() { + assertThatThrownBy(() -> sut.create(null)).isInstanceOf(IllegalArgumentException.class); + } +} \ No newline at end of file diff --git a/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserFinderTest.java b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserFinderTest.java new file mode 100644 index 0000000..ad3a2dc --- /dev/null +++ b/spring-data-elasticsearch-poc/opensearch/src/test/java/com/poc/opensearch/application/UserFinderTest.java @@ -0,0 +1,69 @@ +package com.poc.opensearch.application; + +import com.poc.opensearch.domain.User; +import com.poc.opensearch.domain.UserRepository; +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class UserFinderTest { + + private static final String ANY_STRING = "String"; + + @Mock + UserRepository repository; + + @Mock + private User user; + + UserFinder sut; + + @BeforeEach + void setUp() { + sut = new UserFinder(repository); + } + + @Test + void ID_로_조회_시_유저가_없으면_예외가_발생한다() { + given(repository.findById(ANY_STRING)).willReturn(Optional.empty()); + + assertThatThrownBy(() -> sut.findById(ANY_STRING)).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void ID_로_조회한다() { + given(repository.findById(ANY_STRING)).willReturn(Optional.of(user)); + + sut.findById(ANY_STRING); + + verify(repository).findById(ANY_STRING); + } + + @Test + void NAME_으로_조회한다() { + given(repository.findAllByNameContaining(ANY_STRING)).willReturn(Lists.newArrayList(user)); + + sut.findAllByName(ANY_STRING); + + verify(repository).findAllByNameContaining(ANY_STRING); + } + + @Test + void PHONE_NUMBER_로_조회한다() { + given(repository.findAllByPhoneNumberContaining(ANY_STRING)).willReturn(Lists.newArrayList(user)); + + sut.findAllByPhoneNumber(ANY_STRING); + + verify(repository).findAllByPhoneNumberContaining(ANY_STRING); + } +} \ No newline at end of file