Skip to main content

Transaction & Distributed Systems 分布式

Transaction 事务

1. What is Transactional Annotation (@transactional)?

  • Generally the @Transactional annotation is written at the service level.
  • It is used to combine more than one writes on a database as a single atomic operation.
  • In the case of read operations it is not useful and so it is in case of a single atomic write. You are using it in a single read (select) so adding or removing the @Transactional annotation has no impact. 单次读写操作时,删除或使用 @Transactional 没有影响
  • 是本地事务,即单数据节点的情况下保持事务,无法保证跨库的分布式事务

2. Does by default all the methods of JpaRepository are Transactional?

  • Only CRUD methods are by default marked as transactional.
  • If you are using custom query methods you should explicitly mark it with @Transactional annotation.
@Repository
public interface UserRegistrationRepository extends JpaRepository<UserRegistration, Long> {

UserRegistration findByEmail(String email);

@Transactional
void deleteByEmail(String email);

}

3. How will you write a transaction? How will you introduce transactions into your Spring Boot code?

  • 如何引入依赖库: In Spring Boot, you can introduce transactions by adding the spring-tx dependency to your pom.xml file and configuring your data source to use a transaction manager.
@Service
public class UserService {

@Autowired
private UserRepository userRepository;

@Transactional
public void updateUsername(Long userId, String newUsername) {
User user = userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException());
user.setUsername(newUsername);
userRepository.save(user);
}
}

In this example, the updateUsername method is marked with the @Transactional annotation, which tells Spring to start a new transaction before executing the method, and to automatically commit the transaction when the method returns successfully, or roll back the transaction if an exception is thrown. 它会在方法返回成功时自动提交事务,如果出现异常则回滚事务被抛出。

Engineering 工程化问题

1. How to track the request process when calling multiple microservices? 调用多个微服务时如何跟踪请求流程

You are building a complex system, there are 4 or 5 different apps connecting together, let's say a app is taking request and other app is doing the validation. The process of all those things are done in the different microservices. You want to track the request and the process, what do you think your design would be? 您正在构建一个复杂的系统,有 4 或 5 个不同的应用程序连接在一起,假设一个应用程序正在接受请求,其他应用程序正在进行验证。所有这些事情的过程都是在不同的微服务中完成的。您想跟踪请求和流程,您认为您的设计会是什么?

Idea - Centralized Logging

One approach is to implement centralized logging, where each microservice logs relevant information about the request and its processing, such as the request payload, start time, end time, status, etc. The logs can be stored in a centralized logging system such as ELK (Elasticsearch, Logstash, and Kibana) or Graylog. 实施集中式日志记录,其中每个微服务记录有关请求及其处理的相关信息

Idea - Tracing 推荐的解决方案

Another approach is to implement tracing, which involves adding unique identifiers (such as trace IDs) to requests as they pass through the different microservices. This makes it possible to follow the path of a request through the system and see how long it took for each microservice to process it. A distributed tracing tool such as Jaeger or Zipkin can be used for this purpose. 实施跟踪,这涉及在请求通过不同的微服务时向其添加唯一标识符(例如跟踪 ID)

Implementation - By Trace ID

  • Generate 生成:
    • Create a unique Trace ID at the first point of entry (e.g., API Gateway).
    • 当请求首次进入系统(例如,通过API网关或第一个接收请求的服务)时,生成一个唯一的Trace ID。
  • Pass along 传递:
    • Send this Trace ID through all microservices using an HTTP header.
    • 在微服务架构中的所有后续调用中,将Trace ID作为一个HTTP头(例如,X-Trace-ID)传递给所有的服务。
  • Log 记录:
    • Include the Trace ID in all log entries across services.
    • 在日志条目中包含Trace ID,以便能够跨多个服务关联日志条目。

Flow Sample 流程解析

  1. Request enters, generate Trace ID. 请求进入API网关,生成一个唯一的Trace ID。
  2. Pass Trace ID through all involved services using HTTP headers. API网关使用HTTP头将Trace ID传递给后端服务。
  3. Include Trace ID in logs and trace events in all services. 后端服务在处理请求时将 Trace ID包含在任何日志条目和服务中。
  4. All services send trace information to the distributed tracing system and send log entries to the centralized log management system. 所有的服务将追踪信息发送到分布式追踪系统,并将日志条目发送到集中式日志管理系统。