REST Web服务的客户端ID生成策略 [英] Client side id generation strategy for REST web service
问题描述
比方说,我想构建一个REST服务来制作看起来像这样的笔记:
Let's say I want to build a REST service for making notes that looks something like this:
GET /notes/ // gives me all notes
GET /notes/{id} // gives the note identified by {id}
DELETE /notes/{id} // delete note
PUT /notes/{id} // creates a new note if there is no note identified by {id}
// otherwise the existing note is updated
由于我希望我的服务是独立的,因此我使用PUT来创建和更新笔记, 这意味着新注释的ID由客户设置/生成.
Since I want my service to be indempotent I'm using PUT to create and update my notes, which implies that the ids of new notes are set/generated by the Client.
我考虑过使用GUID/UUID,但是它们很长,会使记住URL变得很困难.从数据库的角度来看,从性能的角度来看,这么长的字符串id在用作大表的主键时也会很麻烦.
I thought of using GUIDs/UUIDs but they are pretty long and would make remembering the URLs rather dificult. Also from a database perspective such long string ids can be troublesome from a performance point of view when used as primary key in big tables.
您知道一个好的ID生成策略,它会生成短ID,并且可以避免碰撞吗?
Do you know a good id generation strategy, that generates short ids and of course avoids collisions?
推荐答案
系统高度分散是有原因的(例如 mongodb 等),而在集中式关系数据库(或
There is a reason why highly distributed system (like git, mongodb, etc.) use long UUIDs/hashes while centralized relational databases (or svn for that matter) can simply use int
s. There is no easy way of creating short ids on the client-side in a distributed fashion. Either the server handles them or you must live with wasteful ids. Typically they contain encoded timestamp, client/computer id, hashed content, etc.
这就是REST服务通常使用的原因
That's why REST services typically use
POST /notes
进行非幂等保存,然后使用Location:
标头的输出作为响应:
for non-idempotent save and then use the output of Location:
header in response:
Location: /notes/42
这篇关于REST Web服务的客户端ID生成策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!