如何在Spring Boot中开始编写微服务,以免日后头痛

你好!我的名字叫Zhenya,我是Usetech的Java开发人员,最近我一直在从事微服务体系结构的工作,在本文中,我想分享一些要点,当您在Spring Boot上编写新的微服务时要注意这些点。



经验丰富的开发人员可能会发现这些建议很明显,但是这些建议都是取材于实际项目的实践。



1.使控制器变薄



在传统的分层体系结构中,控制器类接受请求并将其路由到服务,而服务则处理业务逻辑。但是,有时在控制器的方法中,您可以找到对输入参数的某种验证,以及将实体转换为DTO的方法。



例如:



@GetMapping
public OperationDto getOperationById(@PathVariable("id") Long id) {

    Optional<Operation> operation = operationService.getById(id);

    if (operation.isEmpty()) {
        return EMPTY_OPERATION_DTO;
    }

    OperationDto result = mapperFacade.map(operation.get(), OperationDto.class);
    return result;
}


一方面,映射仅占用一行,并且检查结果是否缺失看起来很合乎逻辑。然而,在这种情况下,违反了控制器的唯一责任原则。尽管验证或映射很简单,但是控制器方法中的几行额外的代码根本不会引人注目,但是在将来,验证和映射的逻辑可能会变得更加复杂,因此很明显,控制器不仅接受和重定向请求,而且还处理商业逻辑。



, , , "", , DTO.



:



@GetMapping
public OperationDto getOperationById(@PathVariable("id") Long id) {
    return operationService.getById(id);
}


:



public OperationDto getById(Long id) {

    Optional<Operation> operationOptional = ... //  operation

    return operationOptional
        .map(operation -> mapperFacade.map(operation, OperationDto.class))
        .orElse(EMPTY_OPERATION_DTO);
}


2. DTO



, DTO REST API, DTO Kafka. , REST Kafka, , DTO . , DTO .



, DTO, , DTO, , . DTO , .



3. WARN-,



, , , , , Spring Boot , , .



WARN, "" Spring Boot 2 Hibernate:

spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning



, - Spring Boot 2 Open Session In View, Hibernate HTTP-.



Open Session In View LazyInitializationException, , Hibernate , , -. , , , ( n+1). .



, Open Session In View , — application.yml :



spring:
  jpa:
    open-in-view: false


4.



, @SpringBootTest , , . , @SpringBootTest, , Spring . , . , , .



:



  • @Import,
  • @ActiveProfiles
  • @MockBean Mockito — , -
  • @TestPropertySource — ,
  • @DirtiesContext — ,


, .. . , :



  • @SpringBootTest
  • @ActiveProfiles("test")
  • protected ( @Autowired) - (@MockBean)


, (@AfterEach), / .



, , , , setUp .



@DirtiesContext.



, - .




All Articles