본문 바로가기
MSA

예제프로젝트 user-service

by 혀눅짱 2023. 6. 22.

MSA 강의에서 진행하는 간단한 커머스 예제 프로젝트 중 유저서비스 부분이다.

 

디스커버리서비스는 기존에 만들어두었단 유레카서버를 그대로 사용하고 유저서비스를 유레카서버에 등록한다.

server:
  port: 0

spring:
  application:
    name : user-service
  h2:
    console:
      enabled: true
      settings:
        web-allow_others: true
      path: /h2-console
  datasource:
    driver-class_name: org.h2.Driver
    url: jdbc:h2:mem:test

eureka:
  instance:
    instance-id: ${spring.cloud.client.hostname}:${spring.application.instance_id:${random.value}}
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka


greeting:
  message: Welcome to the Simple E-commerce

 

포트는 랜덤포트로 설정하고 인스턴스아이디는 어플리케이션이름에 랜던 값을 합친것으로 표시한다.

 

또한 간단한 데이터 crud를 테스트하기위해 인메모리 db인 h2데이터 베이스를 이용한다.

 

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.3.176</version>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>org.modelmapper</groupId>
   <artifactId>modelmapper</artifactId>
   <version>2.3.8</version>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>

그리고 jpa와 spring security사용을 위한 라이브러리를 pom.xml에 명시한다. 

rest api 서버에서는 jpa 엔티티 오브젝트를 절대 dto의 용도 요청값을 받고 응답하기위한 오브젝트로 사용하면 안되서(필드변경시 api스펙에 영향이 직결되며 db구조자체를 외부로 노출시키는것과 같기때문) 별도의 dto를 만들어서 사용하게되는데 엔티티와 dto간의 값전달을 편하게 하기위해 modelmapper 라이브러리를 활용한다.

 

먼저 회원가입 요청 정보를 받을 요청dto이다 

 

@Data
public class RequestUser {

    @NotNull(message = "필수입력 항목입니다.")
    @Size(min = 2, message = "2글자 이상이어야 합니다.")
    @Email
    private String email;
    @NotNull(message = "필수입력 항목입니다.")
    @Size(min = 2, message = "2글자 이상이어야 합니다.")
    private String name;

    @NotNull(message = "필수입력 항목입니다.")
    @Size(min = 8, message = "8글자 이상이어야 합니다.")
    private String pwd;
}

 

간단한 validation 체크도 해준다.

 

@PostMapping("/users")
public ResponseEntity<ResponseUser> createUser(@RequestBody RequestUser user){
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    UserDto userDto = mapper.map(user,UserDto.class);
    userService.createUser(userDto);

    ResponseUser responseUser = mapper.map(userDto, ResponseUser.class);

    return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);
}

컨트롤러 진입후에 modelmapper를 이용해 dto객체에 입력정보를 넣는다.

 

@Override
public UserDto createUser(UserDto userDto) {
    userDto.setUserId(UUID.randomUUID().toString());

    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
    UserEntity userEntity = mapper.map(userDto,UserEntity.class);
    userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd()));

    userRepository.save(userEntity);

    UserDto returnUserDto = mapper.map(userEntity, UserDto.class);

    return returnUserDto;
}

그후 엔티티객체로 변환해서 영속성컨텍스트에 persist하게되는데 이때 패스워드는 시큐리티에서 제공하는 BcryptePasswordEncoder를 사용하게 된다. 이것역시 스프링컨테이너에서 의존성주입을 받기위해 bean으로 등록한다.

 

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {

   public static void main(String[] args) {
      SpringApplication.run(UserServiceApplication.class, args);
   }

   @Bean
   public BCryptPasswordEncoder passwordEncoder(){
      return new BCryptPasswordEncoder();
   }

}

가장최우선인 메인어플리케이션에 빈을 명시해뒀다.

 

레포지토리는 인터페이스 형태로 JpaRepository를 상속하여 사용하였다.

 

포스트맨을 통하여 테스트를 진행해보면

 

json으로 입력정보를 body에 넣어서 요청한다.

 

{
"email": "test@gmail.com",
"name":"테스트2",
"pwd":"test1234"
}
 
ID  EMAIL  ENCRYPTED_PWD  NAME  USER_ID  
1 test@gmail.com $2a$10$dEiqunDl/v50uKQNzF6L.OkGCDbVruUQvHndJWQVB1AfZ7f16sUOS 테스트2 a9f02dd5-7ee3-4294-8087-46684957f3b6

h2데이터베이스에 데이터가 정상적으로 들어왔으며 패스워드 또한 인코딩되었다.

 

사실 jpa강의 커리큘럼을 듣고 간단한 클론프로젝트도 진행해보아서 jpa에 관한 것은 비교적 쉽게 이해가됬고 복습하는 차원이였는데 이제부턴 상품,조회서비스를 만들고 그것들과 통신하는 msa의 방법에 대해 집중해서 공부해보아야겠다.

 

'MSA' 카테고리의 다른 글

RestTemplate  (0) 2023.09.04
RabbitMQ  (0) 2023.09.04
Config service  (0) 2023.09.04
Spring Cloud GateWay  (0) 2023.09.04
Spring Cloud EureKa 서비스 등록  (0) 2023.06.13