Commit 84664387 authored by lemin's avatar lemin

test

parents
Pipeline #177 failed with stages
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/
FROM openjdk:11.0.13-slim
ARG JAR_FILE=build/libs/order-0.0.1-SNAPSHOT.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","/app.jar"]
# Axon Framework 예제
## 0. 개요
이 예제는 쇼핑몰 예제로 CQRS와 SAGA Pattern을 이용해 보상 트랜잭션을 발행하는 예제입니다.
기능은 아래 4가지 기능이 있습니다.
1. product을 등록하고
2. 해당 product을 주문 하고
3. 주문을 하면 product에서 개수를 차감 하고
4. 개수가 부족하면 주문 상태를 CANCELED로 바꾸는 기능
## 1. Axon Server실행
이 프로젝트를 실행 하려면 Axon Server를 먼저 실행 해야 합니다.
아래와 같이 Docker를 이용해 실행 할 수 있습니다.
```
$ docker run -d --name my-axon-server -p 8024:8024 -p 8124:8124 axoniq/axonserver
```
Docker없이 .jar을 다운받아서 바로 실행 할 수 있습니다.
https://download.axoniq.io/axonserver/AxonServer.zip
```
$ java -jar axonserver.jar
```
## 2. API
1. GET /product - 등록한 제품(product)을 조회합니다.
2. GET /order - 등록한 주문을 조회 합니다.
3. POST /product - 제품(product) 등록합니다.
RequestBody
```json
{
"productId":"bedcceac-8587-430c-921c-637d0b151ca2", "quantity":30
}
```
4. POST /order - 주문을 등록 합니다.
RequestBody
```json
{
"name":"버티컬 마우스",
"quantity":30,
"price":10000
}
```
## 실행 방법
1. Axon Server실행
2. Application실행
package com.showcase.synapse.sales;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*")
.allowedMethods(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name()
);
}
}
apiVersion: v1
kind: ConfigMap
metadata:
name: config-axon
data:
AXON_AXONSERVER_SERVERS: localhost:8124
# AXON_AXONSERVER_SERVERS: ec2-15-164-22-248.ap-northeast-2.compute.amazonaws.com:8124
plugins {
id 'org.springframework.boot' version '2.7.2'
id 'io.spring.dependency-management' version '1.0.12.RELEASE'
id 'java'
}
group = 'com.showcase.synapse'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
// implementation 'mysql:mysql-connector-java'
implementation 'org.postgresql:postgresql'
implementation 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// https://mvnrepository.com/artifact/org.axonframework/axon-spring-boot-starter
implementation group: 'org.axonframework', name: 'axon-spring-boot-starter', version: '4.5.14'
implementation group: 'org.axonframework', name: 'axon-configuration', version: "4.5.14"
}
tasks.named('test') {
useJUnitPlatform()
}
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'showcase_sales'
package com.showcase.synapse.filter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//여기에 내가 허용하고자 하는 클라이언트의 url을 입력해 줍니다.
//주의사항 "https://myurl.com/" 처럼 마지막에 '/'를 붙이면 CORS에러가 그대로 발생하게 됩니다.
//response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
response.setHeader("Access-Control-Allow-Origin", "*"); //이렇게 해서 모든 요청에 대해서 허용할 수도 있습니다.
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods","*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization");
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
}else {
chain.doFilter(req, res);
}
}
@Override
public void destroy() {
}
}
package com.showcase.synapse.sales;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MsaSalesApplication {
public static void main(String[] args) {
SpringApplication.run(MsaSalesApplication.class, args);
}
}
package com.showcase.synapse.sales.aggregate;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.CommandHandler;
import org.axonframework.eventsourcing.EventSourcingHandler;
import org.axonframework.modelling.command.AggregateIdentifier;
import org.axonframework.spring.stereotype.Aggregate;
import com.showcase.synapse.sales.command.ChangeQuantityCommand;
import com.showcase.synapse.sales.command.CreateProductCommand;
import com.showcase.synapse.sales.event.ProductCreatedEvent;
import com.showcase.synapse.sales.event.ProductQuantityChangedEvent;
import com.showcase.synapse.sales.saga.ProductSaga;
import java.math.BigDecimal;
import static org.axonframework.modelling.command.AggregateLifecycle.apply;
@Aggregate
@NoArgsConstructor
@Slf4j
public class ProductAggregate {
@AggregateIdentifier
private String id;
// private int quantiy;
@CommandHandler
public ProductAggregate(CreateProductCommand command) {
log.info("[ProductAggregate(CreateProductCommand) > apply new ProductCreatedEvent]");
apply(new ProductCreatedEvent(command.getId(), command.getName(), command.getComment(), command.getPrice()));
}
@EventSourcingHandler
public void createProduct(ProductCreatedEvent event) {
this.id = event.getProductId();
// this.quantiy = event.getQuantity();
}
@CommandHandler
public void changeQuantity(ChangeQuantityCommand command) {
log.info("[@CommandHandler ProductchangeQuantity]");
// if(this.quantiy < command.getQuantity()) throw new IllegalArgumentException("tfy ");
// apply(new ProductQuantityChangedEvent(command.getProductId(), this.quantiy - command.getQuantity()));
}
@EventSourcingHandler
public void changeQuantity(ProductQuantityChangedEvent event) {
// this.quantiy = event.getQuantity();
}
}
package com.showcase.synapse.sales.command;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public class ChangeQuantityCommand {
@TargetAggregateIdentifier
private String productId;
private int quantity;
}
package com.showcase.synapse.sales.command;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.axonframework.modelling.command.TargetAggregateIdentifier;
import java.math.BigDecimal;
@AllArgsConstructor
@Getter
public class CreateProductCommand {
@TargetAggregateIdentifier
private final String id;
private final String name;
private final String comment;
private final BigDecimal price;
// private final Integer quantity;
}
package com.showcase.synapse.sales.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.showcase.synapse.sales.dto.ProductCreateDto;
import com.showcase.synapse.sales.entity.ProductEntity;
import com.showcase.synapse.sales.service.ProductService;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@RestController
@RequestMapping("/api/msa/product")
@CrossOrigin(origins = "*")
public class ProductController {
final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/")
public ResponseEntity<List<ProductEntity>> getProducts() throws ExecutionException, InterruptedException {
List<ProductEntity> productEntities = productService.getProducts();
return ResponseEntity.ok(productEntities);
}
@PostMapping("/")
public ResponseEntity<Map<String, String>> productCreate(@RequestBody ProductCreateDto productCreateDto) {
String productId = productService.createProduct(productCreateDto.getName(),
productCreateDto.getComment(),
BigDecimal.valueOf(productCreateDto.getPrice()));
HashMap<String, String> m = new HashMap<>();
m.put("productId", productId);
m.put("productName", productCreateDto.getName());
return ResponseEntity.ok(m);
}
}
package com.showcase.synapse.sales.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ProductCreateDto {
private String name;
private String comment;
private int price;
}
package com.showcase.synapse.sales.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ProductEntity {
@Id
private String id;
private String name;
private String comment;
private BigDecimal price;
}
package com.showcase.synapse.sales.enums;
public enum OrderStatus {
CREATED, CANCELED
}
package com.showcase.synapse.sales.event;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.math.BigDecimal;
@AllArgsConstructor
@Getter
public class ProductCreatedEvent {
private String productId;
private String name;
private String comment;
private BigDecimal price;
}
package com.showcase.synapse.sales.event;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public class ProductQuantityChangedEvent {
private String productId;
private int quantity;
}
package com.showcase.synapse.sales.event.handler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.EventHandler;
import org.springframework.stereotype.Component;
import com.showcase.synapse.sales.entity.ProductEntity;
import com.showcase.synapse.sales.event.ProductCreatedEvent;
import com.showcase.synapse.sales.event.ProductQuantityChangedEvent;
import com.showcase.synapse.sales.repository.ProductRepository;
@Component
@AllArgsConstructor
@Slf4j
public class ProductEventHandler {
private final ProductRepository productRepository;
@EventHandler
protected void saveProduct(ProductCreatedEvent productCreatedEvent) {
log.info("ProductCreatedEvent 이벤트 받음?");
log.info("ProductEventHandler > [ProductCreatedEvent] productCreatedEvent");
ProductEntity productEntity = new ProductEntity();
productEntity.setId(productCreatedEvent.getProductId());
productEntity.setName(productCreatedEvent.getName());
productEntity.setComment(productCreatedEvent.getComment());
productEntity.setPrice(productCreatedEvent.getPrice());
productRepository.save(productEntity);
}
@EventHandler
protected void changeQuantity(ProductQuantityChangedEvent productQuantityChangedEvent) {
log.info("ProductQuantityChangedEvent 이벤트 받음?");
log.info("[ProductQuantityChangedEvent]");
ProductEntity productEntity = productRepository.findById(productQuantityChangedEvent.getProductId()).get();
// log.info("[{}] quantity:{}", productEntity.getName(), productEntity.getQuentity());
// productEntity.setQuentity(productQuantityChangedEvent.getQuantity());
productRepository.save(productEntity);
}
}
package com.showcase.synapse.sales.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.time.LocalDateTime;
@AllArgsConstructor
@Getter
public class ErrorMessage {
private LocalDateTime dateTime;
private String message;
}
package com.showcase.synapse.sales.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
@RestControllerAdvice
public class ExceptionManager {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exceptionHandler(Exception ex, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(
new ErrorMessage(LocalDateTime.now(),
ex.getMessage()));
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<?> illegalArgumentExceptionHandler(Exception ex, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(
new ErrorMessage(LocalDateTime.now(),
ex.getMessage()));
}
}
package com.showcase.synapse.sales.query;
public class GetProductsQuery {
}
package com.showcase.synapse.sales.query.handler;
import java.util.List;
import org.axonframework.queryhandling.QueryHandler;
import org.springframework.stereotype.Component;
import com.showcase.synapse.sales.entity.ProductEntity;
import com.showcase.synapse.sales.query.GetProductsQuery;
import com.showcase.synapse.sales.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Component
@RequiredArgsConstructor
@Slf4j
public class ProductQueryHandler {
private final ProductRepository productRepository;
@QueryHandler
protected List<ProductEntity> on(GetProductsQuery query) {
log.info("---product query---");
return productRepository.findAll();
}
}
package com.showcase.synapse.sales.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.showcase.synapse.sales.entity.ProductEntity;
public interface ProductRepository extends JpaRepository<ProductEntity, String> {
}
package com.showcase.synapse.sales.saga;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.spring.stereotype.Saga;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
//@Saga
@Slf4j
public class ProductSaga {
@Autowired
private transient CommandGateway commandGateway;
}
package com.showcase.synapse.sales.service;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.messaging.responsetypes.ResponseTypes;
import org.axonframework.queryhandling.QueryGateway;
import org.springframework.stereotype.Service;
import com.showcase.synapse.sales.command.CreateProductCommand;
import com.showcase.synapse.sales.entity.ProductEntity;
import com.showcase.synapse.sales.query.GetProductsQuery;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class ProductService {
private final CommandGateway commandGateway;
private final QueryGateway queryGateway;
public ProductService(CommandGateway commandGateway, QueryGateway queryGateway) {
this.commandGateway = commandGateway;
this.queryGateway = queryGateway;
}
public String createProduct(String name, String comment, BigDecimal price) {
log.info("[@Service createProduct] new CreateProductCommand");
// command생성
CreateProductCommand createProductCommand = new CreateProductCommand(
UUID.randomUUID().toString(), name, comment, price
);
System.out.println("test");
// 여기
// 생성한 command전송(비동기)
String returnValue = commandGateway.sendAndWait(createProductCommand);
System.out.printf("returnValue: %s \n", returnValue);
return returnValue;
}
public List<ProductEntity> getProducts() throws ExecutionException, InterruptedException {
return queryGateway.query(new GetProductsQuery(),
ResponseTypes.multipleInstancesOf(ProductEntity.class)).get();
}
}
axon:
serializer:
general: xstream
axonserver:
servers: localhost:8124
server:
port : 9090
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/postgres
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://localhost:3306/msatest
username: postgres
password: admin
jpa:
# show-sql: true
hibernate:
ddl-auto: update
# dialect: org.hibernate.dialect.H2Dialect
properties:
format_sql: true
\ No newline at end of file
package com.axon.order;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AxonShoppingmallOrderApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment