[Spring Cloud] Catalogs Microservice - 생성

jsieon97·2023년 3월 12일
0

Dependencies

  • JPA
  • Spring Web
  • Eureka Discovery Client
  • h2 (1.3이하 버전)
  • modelmapper (2버전이상)
  • lombok
  • Spring Devtools

property 설정

// application.yml

server:
  port: 0

spring:
  application:
    name: catalog-service
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
      path: /h2-console
  jpa:
    hibernate:
      ddl-auto: create-drop
    show-sql: true
    generate-ddl: true
    database: h2
    defer-datasource-initialization: true
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb
#    username: sa
#    password: 1234

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

database: h2
defer-datasource-initialization: true
옵션은 테이블이 자동 생성 안될때 추가해준다.

자동으로 INSERT될 데이터 생성

파일 경로 {ContextPath}\catalog-service\src\main\resources

// data.sql

insert into catalog (product_id, product_name, stock, unit_price)
values ('CATALOG-001', 'Berlin', 100, 1500);

insert into catalog (product_id, product_name, stock, unit_price)
values ('CATALOG-002', 'Tokyo', 110, 1000);

insert into catalog (product_id, product_name, stock, unit_price)
values ('CATALOG-003', 'Stockholm', 120, 2000);

Entity 클래스,인터페이스 생성

// CatalogEntity.java

@Data
@Entity
@Table(name = "catalog")
public class CatalogEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false, length = 120, unique = true)
    private String productid;
    @Column(nullable = false)
    private String productName;
    @Column(nullable = false)
    private Integer stock;
    @Column(nullable = false)
    private Integer unitPrice;

    @Column(nullable = false, updatable = false, insertable = false)
    @ColumnDefault(value = "CURRENT_TIMESTAMP") // 현재 시각을 default로 생성
    private Date createAt;
}
// CatalogRepository.java

public interface CatalogRepository extends CrudRepository<CatalogEntity, Long> {
    CatalogEntity findByProductId(String productId);
}

Dto와 반환(Response)클래스 생성

// CatalogDto.java

@Data
public class CatalogDto implements Serializable {
    private String productId;
    private Integer qty;
    private Integer unitPrice;
    private Integer totalPrice;

    private String orderId;
    private String userId;
}
// ResponseCatalog

@Data
@JsonInclude(JsonInclude.Include.NON_NULL) // NULL 데이터 반환 X
public class ResponseCatalog {
    private String productId;
    private String productName;
    private Integer unitPrice;
    private Integer stock;

    private Date createAt;
}

Service 생성

// CatalogService.java

public interface CatalogService {
    Iterable<CatalogEntity> getAllCatalogs();
}
// CatalogServiceImpl.java

@Data
@Slf4j
@Service
public class CatalogServiceImpl implements CatalogService{
    private CatalogRepository catalogRepository;

    public CatalogServiceImpl(CatalogRepository catalogRepository) {
        this.catalogRepository = catalogRepository;
    }

    @Override
    public Iterable<CatalogEntity> getAllCatalogs() {
        return catalogRepository.findAll();
    }
}

Controller 생성

@RestController
@RequestMapping("/catalog-service")
public class CatalogController {
    private Environment env;
    private CatalogService catalogService;

    @Autowired
    public CatalogController(Environment env, CatalogService catalogService) {
        this.env = env;
        this.catalogService = catalogService;
    }

    @GetMapping("/health_check")
    public String status() {
        return String.format("It's Working in Catalog Service on PORT %s",
                env.getProperty("local.server.port"));
    }

    @GetMapping("/catalogs")
    public ResponseEntity<List<ResponseCatalog>> getUsers() {
        Iterable<CatalogEntity> catalogList = catalogService.getAllCatalogs();

        List<ResponseCatalog> result = new ArrayList<>();
        catalogList.forEach(v -> {
            result.add(new ModelMapper().map(v, ResponseCatalog.class));
        });

        return ResponseEntity.status(HttpStatus.OK).body(result);
    }
}

테이블 INSERT 체크

API Gateway에 Catalog Service 추가


	...
    
spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      default-filters:
        - name: GlobalFilter
          args:
            baseMessage: Spring Cloud Gateway GlobalFilter
            preLogger: true
            postLogger: true
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/user-service/**
        - id: catalog-service
          uri: lb://CATALOG-SERVICE
          predicates:
            - Path=/catalog-service/**

Postman 테스트

profile
개발자로써 성장하는 방법

0개의 댓글