以下使用 Spring Boot、Hibernate、JpaRepository、CockroachDB 和 Kotlin 的最小 CRUD 示例生成org.springframework.orm.jpa.JpaSystemException
/ org.hibernate.TransactionException
。
有问题的实体Thing
只有两个字段:
@Entity
data class Thing (
@Id
var id: Long,
var value: String
)
为了使这篇文章简短,我将实际的源文件存储在 gists 中:
./src/main/kotlin/ThingService.kt
./src/main/resources/application.properties
使用这些文件,可以使用以下命令重现问题(在我的情况下是在 Ubuntu 16.04 上)。
下载并初始化 CockroachDB:
# download
wget -qO- https://binaries.cockroachdb.com/cockroach-v1.1.5.linux-amd64.tgz | tar xvz
# start
./cockroach-v1.1.5.linux-amd64/cockroach start --insecure
# leave terminal open in background
# init
cockroach sql --insecure -e "CREATE USER root WITH PASSWORD '123';"
cockroach sql --insecure -e "CREATE DATABASE things_db;"
cockroach sql --insecure -e "GRANT ALL ON DATABASE things_db TO root;"
运行数据服务:
gradle bootRun
# leave terminal open in background
运行压力测试:
python3 stress_test.py
stress_test.py
同时向服务发送PUT
请求和GET
请求(按值查找)。大多数请求工作正常,但在输出之间看起来如下:
PUT OK
find OK
PUT OK
find OK
find OK
find OK
PUT ERROR: {"timestamp":"2018-03-17T16:00:24.616+0000","status":500,"error":"Internal Server Error","message":"Unable to commit against JDBC Connection; nested exception is org.hibernate.TransactionException: Unable to commit against JDBC Connection","path":"/thing/"}
find OK
PUT OK
Spring 应用程序的日志显示了更多详细信息:
2018-03-17 17:00:24.615 ERROR 3547 --- [nio-8082-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Unable to commit against JDBC Connection; nested exception is org.hibernate.TransactionException: Unable to commit against JDBC Connection] with root cause
org.postgresql.util.PSQLException: ERROR: restart transaction: HandledRetryableTxnError: TransactionRetryError: retry txn (RETRY_SERIALIZABLE): "sql txn" id=1cb57665 key=/Table/51/1/11125601/0 rw=true pri=0.04354217 iso=SERIALIZABLE stat=PENDING epo=0 ts=1521302424.604752770,1 orig=1521302424.604725980,0 max=1521302424.604725980,0 wto=false rop=false seq=3
没有并发写入。所有写入都是严格顺序的。仅当并发读取起作用时才会出现此问题。但是我认为这不应该导致需要重试任何事务。我的数据库连接配置是否有问题,或者可能是什么问题?