Skip to content

Commit

Permalink
#6 refactor: 전체 서비스 코드 품질 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
downfa11 committed Dec 30, 2024
1 parent 49b019f commit a28f8a7
Show file tree
Hide file tree
Showing 40 changed files with 497 additions and 412 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
> 20세기 말. 한국 근대사를 재조명해 역사의식을 키우기 위해 텀블벅 후원 준비중인 기능성 게임

![resistance](https://github.com/user-attachments/assets/11bce376-1c21-4cb8-8f5f-0f59f4691945)

![main.png](main.png)

사용자 데이터 활용,공지사항 및 텀블벅 후원 상품 제공 등을 위해 웹서버를 구현했습니다.

Expand All @@ -17,9 +17,7 @@
Spring MVC, Spring data JPA, Kafka, Redis(Lettuce), Vault, MySQL

<br>
</br>

![resistance_architecture.png](resistance_architecture.png)

다음과 같이 하위 도메인별로 모듈을 분해했습니다.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,36 +56,40 @@ public TaskConsumer(@Value("${kafka.clusters.bootstrapservers}") String bootstra
consumer.subscribe(Collections.singletonList(topic));
Thread consumerThread = new Thread(() -> {
try {
while (true) {
ObjectMapper mapper = new ObjectMapper();
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> record : records) {
System.out.println("Received message: " + record.value());

try {
Task tasks = mapper.readValue(record.value(), Task.class);
List<SubTask> subTaskList = tasks.getSubTaskList();
processConsumerThread();
} finally {
consumer.close();
}
});
consumerThread.start();
}

for (SubTask subTask : subTaskList) {
if(subTask.getTaskType().equals("membership"))
subTask = getUserDataByMembershipId(subTask);
private void processConsumerThread(){
while (true) {
ObjectMapper mapper = new ObjectMapper();
ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(1));
for (ConsumerRecord<String, String> record : records) {
System.out.println("Received message: " + record.value());

else if(subTask.getTaskType().equals("register"))
subTask = Register(subTask);
}
try {
Task tasks = mapper.readValue(record.value(), Task.class);
List<SubTask> subTaskList = tasks.getSubTaskList();

this.taskResultProducer.sendTaskResult(tasks.getTaskID(), tasks);
for (SubTask subTask : subTaskList) {
if(subTask.getTaskType().equals("membership"))
subTask = getUserDataByMembershipId(subTask);

} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
else if(subTask.getTaskType().equals("register"))
subTask = Register(subTask);
}

this.taskResultProducer.sendTaskResult(tasks.getTaskID(), tasks);

} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
} finally {
consumer.close();
}
});
consumerThread.start();
}
}

private SubTask getUserDataByMembershipId(SubTask subTask){
Expand Down Expand Up @@ -113,25 +117,11 @@ private SubTask Register(SubTask subTask){
Long membershipId = Long.parseLong(subTask.getMembersrhipId());
String membershipName = (String) subTask.getData();
try {
UserDataJpaEntity jpaEntity = registerUserDataPort.createUserData(
new UserData.UserId(membershipId),
new UserData.UserName(membershipName),
new UserData.UserGold(0),
new UserData.UserHighscore(0),
new UserData.UserEnergy(0),
new UserData.UserScenario(0),
new UserData.UserHead("0"),
new UserData.UserBody("0"),
new UserData.UserArm("0"),
new UserData.UserHealth(100),
new UserData.UserAttack(15),
new UserData.UserCritical(3),
new UserData.UserDurability(10)
);

UserDataJpaEntity jpaEntity = createUserDataEntity(membershipId, membershipName);
log.info(jpaEntity.getUserId()+"번 데이터인 "+membershipId+" 사용자를 생성했습니다.");
if(jpaEntity!=null)
subTask.setStatus("success");

String status = jpaEntity!=null ? "success" : "fail";
subTask.setStatus(status);

} catch(RuntimeException e){
log.error("Error processing subatsk : "+e.getMessage());
Expand All @@ -141,4 +131,21 @@ private SubTask Register(SubTask subTask){

return subTask;
}

private UserDataJpaEntity createUserDataEntity(Long membershipId, String membershipName){
return registerUserDataPort.createUserData(
new UserData.UserId(membershipId),
new UserData.UserName(membershipName),
new UserData.UserGold(0),
new UserData.UserHighscore(0),
new UserData.UserEnergy(0),
new UserData.UserScenario(0),
new UserData.UserHead("0"),
new UserData.UserBody("0"),
new UserData.UserArm("0"),
new UserData.UserHealth(100),
new UserData.UserAttack(15),
new UserData.UserCritical(3),
new UserData.UserDurability(10));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,7 @@ ResponseEntity<UserData> registerUserData(@RequestBody RegisterUserDataRequest r
if(memberId != request.getUserId())
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();

RegisterUserDataCommand command = RegisterUserDataCommand.builder()
.userId(request.getUserId())
.name(request.getName())
.gold(request.getGold())
.highscore(request.getHighscore())
.energy(request.getEnergy())
.scenario(request.getScenario())
.head(request.getHead())
.body(request.getBody())
.arm(request.getArm())
.health(request.getHealth())
.attack(request.getAttack())
.critical(request.getCritical())
.durability(request.getDurability())
.build();

RegisterUserDataCommand command = createRegisterUserDataCommand(request);
UserData userData = registerUserDataUseCase.registerUserData(command);
return ResponseEntity.ok(userData);
}
Expand All @@ -59,22 +44,7 @@ ResponseEntity<UserData> modifyUserDataByUserId(@RequestBody ModifyUserDataReque
if(memberId != request.getUserId())
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();

ModifyUserDataCommand command = ModifyUserDataCommand.builder()
.userId(request.getUserId())
.gold(request.getGold())
.highscore(request.getHighscore())
.energy(request.getEnergy())
.scenario(request.getScenario())
.head(request.getHead())
.body(request.getBody())
.arm(request.getArm())
.health(request.getHealth())
.attack(request.getAttack())
.critical(request.getCritical())
.durability(request.getDurability())
.build();


ModifyUserDataCommand command = createModifyUserDataCommand(request);
UserData userData = modifyUserDataUseCase.modifyUserData(command);
return ResponseEntity.ok(userData);
}
Expand All @@ -89,4 +59,39 @@ ResponseEntity<UserData> findUserDataByUserId(@PathVariable Long userId){
UserData userData = findUserDataUseCase.findUserData(command);
return ResponseEntity.ok(userData);
}

private RegisterUserDataCommand createRegisterUserDataCommand(RegisterUserDataRequest request){
return RegisterUserDataCommand.builder()
.userId(request.getUserId())
.name(request.getName())
.gold(request.getGold())
.highscore(request.getHighscore())
.energy(request.getEnergy())
.scenario(request.getScenario())
.head(request.getHead())
.body(request.getBody())
.arm(request.getArm())
.health(request.getHealth())
.attack(request.getAttack())
.critical(request.getCritical())
.durability(request.getDurability())
.build();
}

private ModifyUserDataCommand createModifyUserDataCommand(ModifyUserDataRequest request){
return ModifyUserDataCommand.builder()
.userId(request.getUserId())
.gold(request.getGold())
.highscore(request.getHighscore())
.energy(request.getEnergy())
.scenario(request.getScenario())
.head(request.getHead())
.body(request.getBody())
.arm(request.getArm())
.health(request.getHealth())
.attack(request.getAttack())
.critical(request.getCritical())
.durability(request.getDurability())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ns.dedicated.application.port.out;
package com.ns.business.application.port.out;

import com.ns.common.Task;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ns.business;
package com.ns.business.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ns.business;
package com.ns.business.config;


import org.springframework.context.annotation.Configuration;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ns.business;
package com.ns.business.config;


import io.swagger.v3.oas.models.OpenAPI;
Expand Down
7 changes: 2 additions & 5 deletions common/src/main/java/com/ns/common/LoggingAspect.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
package com.ns.common;

import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class LoggingAspect {

private final LoggingProducer loggingProducer;

public LoggingAspect(LoggingProducer loggingProducer) {this.loggingProducer=loggingProducer;}

@Before("execution(* com.ns.*.adapter.in.web.*.*(..))")
public void beforeMethodExecution(@NotNull JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
// logging
loggingProducer.sendMessage("logging","Before executing method: "+methodName);


}
}
3 changes: 1 addition & 2 deletions common/src/main/java/com/ns/common/LoggingProducer.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ public void sendMessage(String key, String value) {
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
producer.send(record, (metadata, exception) -> {
if (exception == null) {
log.info("Message sent successfully. Topic : " + metadata.topic() + " Offset: " + metadata.offset());
log.info(metadata.toString());
log.info("Message sent successfully. Topic : " + metadata.topic() + " Offset: " + metadata.offset() + ", data: " + metadata);
}
else exception.printStackTrace();

Expand Down
2 changes: 1 addition & 1 deletion common/src/main/java/com/ns/common/SubTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
public class SubTask {
private String membersrhipId;
private String subTaskName;
private String taskType; // banking, membership
private String taskType;
private String status; //ready, success, fail
private Object data;
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public class ExchangeController {

@GetMapping("/rates")
public ExchangeRateResponse getExchangeRates(){

Long memberId = jwtTokenProvider.getMembershipIdbyToken();

if(memberId!=adminId){
Expand All @@ -33,11 +32,8 @@ public ExchangeRateResponse getExchangeRates(){

@GetMapping("init")
public ExchangeRateResponse initExchangeRates() { exchangeUseCase.initExchangeRates();


Long memberId = jwtTokenProvider.getMembershipIdbyToken();


if(memberId!=adminId){
throw new RuntimeException("not allow initExchangeRates - id:"+memberId);
}
Expand All @@ -58,8 +54,6 @@ public ExchangeRateResponse updateExchangeRates(){

@PostMapping("/set/{money}")
public ExchangeRateResponse setExchangeRates(@PathVariable String money){


Long memberId = jwtTokenProvider.getMembershipIdbyToken();

if(memberId!=adminId){
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ns.dedicated;
package com.ns.dedicated.adpater.out;

import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.http.HttpStatus;
Expand Down
Loading

0 comments on commit a28f8a7

Please sign in to comment.