database - 在进程之间共享 Postgres(或其他 DBMS)事务上下文
问题描述
单体应用程序设计中的一种常见模式是将业务逻辑委托给专用服务,将开放事务作为例如javax.persistence.EntityTransaction
Java 中的实例或sql.Transaction
Go 中的实例传递。
去例子:
// business.go
type BusinessLogicService interface {
DoSomething(tx *sql.Transaction)
}
type businessLogicService struct {
}
func (s *BusinessLogicService) DoSomething(tx *sql.Transaction) {
tx.ExecuteContext(.....)
}
func NewBusinessLogicService() {
return &businessLogicService{}
}
// server.go
ctx := context.Background()
tx, err := db.BeginTx(ctx)
if err != nil {
log.Fatal(err)
}
bls := business.NewBusinessLogicService()
bls.DoSomething(tx)
tx.Commit()
在每个组件都以不同的语言/运行时实现的架构中是否可以实现相同的效果?在这样的应用程序中,Postgres 负责与 DB 事务相关的“簿记”。在我看来,应该可以将事务的类似“句柄”传递给另一个进程以读取其状态和附加操作。
例如,等效的业务逻辑作为 gRPC 服务提供,定义如下:
message TransactionInfo {
string transaction_id = 1;
}
message DoSomethingRequest {
TransactionInfo transaction_info = 1;
}
message DoSomethingResponse {
}
service BusinessLogicService {
rpc DoSomething(DoSomethingRequest) returns (DoSomethingResponse)
}
服务器处理BEGIN
事务并传递对此 BusinessLogicService 的引用。
ctx := context.Background()
tx, err := db.BeginTx(ctx)
if err != nil {
log.Fatal(err)
}
conn, err := grpc.Dial(*serverAddr, opts...)
if err != nil {
...
}
defer conn.Close()
bls := pb.NewBusinessLogicClient()
/// SOMEHOW PASS THE TX OBJECT TO THE REMOTE SERVICE
txObj := &pb.TransactionInfo{....???????????.....}
result := bls.DoSomething(txObj)
tx.Commit()
这对 Postgres 或其他 DBMS 可行吗?
解决方案
推荐阅读
- azure - Azure 网站将一个 https URL 重定向到同一个域的另一个 https URL
- angular - 在 Angular 测试中使用模拟服务创建类实例
- javascript - 如果不存在则获取 SVG 路径
- javascript - AJAX 收到帖子时启动 javascript
- python-3.x - 使用 Discord.py,有没有办法读取嵌入的消息?
- python - 虚拟环境和基础环境同时激活
- jupyter-notebook - Altair 保护程序 ValueError:不支持的格式:'png'
- python - 使用 Python 生成二元组的问题
- c++ - 添加相邻像素的问题
- postgresql - 如何在基于多边形的表中创建空间约束?